如果我理解正确,那么您希望删除整个数据帧中的所有空格,我猜您使用的代码有助于删除列名中的空格.我觉得你应该试试这个:
apply(myData,2,function(x)gsub('\\s+', '',x))
希望这能奏效.
但是,这将返回一个矩阵,如果要将其更改为数据帧,请执行以下操作:
as.data.frame(apply(myData,2,function(x)gsub('\\s+', '',x)))
EDIT In 2020:
将lapply
和trimws
函数与both=TRUE
一起使用可以删除前导和尾随空格,但不能删除其中的空格.因为OP没有提供输入数据,所以我添加了一个虚拟示例来生成结果.
DATA:
df <- data.frame(val = c(" abc"," kl m","dfsd "),val1 = c("klm ","gdfs","123"),num=1:3,num1=2:4,stringsAsFactors = FALSE)
#situation: 1(使用基数R),当我们想要删除字符串值中的空格only at the leading and trailing ends NOT inside时,我们可以使用trimws
cols_to_be_rectified <- names(df)[vapply(df, is.character, logical(1))]
df[,cols_to_be_rectified] <- lapply(df[,cols_to_be_rectified], trimws)
# situation: 2(使用Base R),当我们想要删除字符列中数据帧中每个位置的空格时(inside of a string as well as at the leading and trailing ends).
(This was the initial solution proposed using apply, please note a solution using apply seems to work but would be very slow, also the with the question its apparently not very clear if OP really wanted to remove leading/trailing blank or every blank in the data)
cols_to_be_rectified <- names(df)[vapply(df, is.character, logical(1))]
df[,cols_to_be_rectified] <- lapply(df[,cols_to_be_rectified], function(x)gsub('\\s+','',x))
## situation: 1(使用data.table,仅删除前导空格和尾随空格)
library(data.table)
setDT(df)
cols_to_be_rectified <- names(df)[vapply(df, is.character, logical(1))]
df[,c(cols_to_be_rectified) := lapply(.SD, trimws), .SDcols = cols_to_be_rectified]
Output从situation1:
val val1 num num1
1: abc klm 1 2
2: kl m gdfs 2 3
3: dfsd 123 3 4
## situation: 2(使用data.table,删除每个内部空白以及前导/尾随空白)
cols_to_be_rectified <- names(df)[vapply(df, is.character, logical(1))]
df[,c(cols_to_be_rectified) := lapply(.SD, function(x)gsub('\\s+', '', x)), .SDcols = cols_to_be_rectified]
Output从situation2:
val val1 num num1
1: abc klm 1 2
2: klm gdfs 2 3
3: dfsd 123 3 4
请注意第2行中两种情况的输出之间的差异:您可以看到,对于trimws
,我们可以删除前导空格和尾随空格,但是对于正则表达式解决方案,我们可以删除每个空格.
我希望这有帮助,谢谢