应用gsub各种列 - Applying gsub to various columns

- 此内容更新于:2016-02-24
主题:

什么是最有效的方法适用于各种列?以下不工作我怎么能最有效地将“%”符号指定列。我可以把它应用到整个dataframe吗?这将是有用的情况下我不知道列的百分比。

原文:

What is the most efficient way to apply gsub to various columns? The following does not work

x1=c("10%","20%","30%")
x2=c("60%","50%","40%")
x3 = c(1,2,3)
x = data.frame(x1,x2,x3)
per_col = c(1,2)
x = gsub("%","",x[,per_col])

How can I most efficiently drop the "%" sign in specified columns. Can I apply it to the whole dataframe? This would be useful in the case where I don't know where the percentage columns are.

解决方案:
您可以使用它来将它应用到整个data.frame
原文:

You can use apply to apply it to the whole data.frame

apply(x, 2, function(y) as.numeric(gsub("%", "", y)))
     x1 x2 x3
[1,] 10 60  1
[2,] 20 50  2
[3,] 30 40  3
解决方案:
或者,你可以试着解决方案:
原文:

Or, you could try the lapply solution:

as.data.frame(lapply(x, function(y) gsub("%", "", y)))

  x1 x2 x3
1 10 60  1
2 20 50  2
3 30 40  3
解决方案:
第一个答案工作但是要小心与字符串:如果您正在使用的@docendodiscimus的回答将返回。如果你想保持你列的内容字符串只是删除表转换成一个数据帧后:
原文:

The first answer works but be careful if you are using data.frame with string: the @docendo discimus's answer will return NAs.

If you want to keep the content of your column as string just remove the as.numeric and convert your table into a data frame after :

as.data.frame(apply(x, 2, function(y) as.numeric(gsub("%", "", y))))
     x1 x2 x3
[1,] 10 60  1
[2,] 20 50  2
[3,] 30 40  3
网友:这也是@info_seekeR提出的解决方案

(原文:This is also in a way the solution proposed @info_seekeR)