R 从字符串中删除填充
我有一个dataframe:dat,如下所示R 从字符串中删除填充,r,R,我有一个dataframe:dat,如下所示 CODE GROUP SET 1 100 6000 20.3 2 100 7000 30.1 3 DEF 8000 120 我使用下面的语句格式化准备插入到XML中: sprintf("<rows>%s</rows>", paste(apply(dat, 1, function(x) { paste("<row
CODE GROUP SET
1 100 6000 20.3
2 100 7000 30.1
3 DEF 8000 120
我使用下面的语句格式化准备插入到XML中:
sprintf("<rows>%s</rows>", paste(apply(dat, 1, function(x) {
paste("<row>", paste(x, collapse="|"), "</row>", sep="")
}), collapse=""))
<rows><row>100|6000| 20.3</row><row>100|6000| 30.1</row><row>DEF|8000| 120</row><row>
sprintf(“%s”),粘贴(应用(dat,1,函数(x){
粘贴(“,粘贴(x,collapse=“|”)”,sep=“”)
}),collapse=“”))
100 | 6000 | 20.3100 | 6000 | 30.1DEF | 8000 | 120
问题是第三列中填充了空格。我认为这与sprintf中的%s有关。有什么办法可以阻止这一行为或删除空间吗?我使用
gsub(" ","",a, fixed=TRUE)
之所以有空格,是因为
apply
在dat
上调用as.matrix
,以及as.matrix.data.frame
方法如何将data.frame转换为字符矩阵。一个更简单的解决方案是对data.frame使用do.call
,而不是apply
dat <- structure(list(CODE = structure(c(1L, 1L, 2L), .Label = c("100",
"DEF"), class = "factor"), GROUP = c(6000L, 7000L, 8000L), SET = c(20.3,
30.1, 120)), .Names = c("CODE", "GROUP", "SET"), class = "data.frame",
row.names = c("1", "2", "3"))
# paste all the rows of dat together
datRows <- do.call(paste, c(dat, sep="|"))
# add </row> [something]ML tags
Row <- paste0("<row>", datRows, "</row>", collapse="")
# add </rows> tags
Rows <- sprintf("<rows>%s</rows>", Row)
dat它与apply
如何调用as.matrix
ondat
以及as.matrix.data.frame
方法如何将data.frame转换为字符矩阵有关。我对其进行了排序-请参阅答案