从字符串中删除填充

时间:2014-11-12 15:13:00

标签: r

我有一个数据帧: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>", 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有关。我有什么想法可以阻止它或剥离空间吗?

2 个答案:

答案 0 :(得分:1)

我使用

剥离了空格
gsub(" ","",a, fixed=TRUE)

答案 1 :(得分:1)

因为applyas.matrix上调用dat以及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)
相关问题