For loop deleting "," in factor variables to make them numeric (R 用户)

For loop deleting "," in factor variables to make them numeric (R user)

我尝试从数据框 (df) 的一组变量中删除所有“,”。对于单个变量(例如债务),我成功 运行:

df$debt <- as.numeric(gsub(",","",df$debt))

它完全符合我的要求(即将因子变量“1,324,234.35”覆盖为数字“1324234.35”)。因此,我使用变量列表创建了以下 for 循环:

dflist <- c("debt","fundequity","age","coempl","corev")
for (i in dflist) {
  df$i <- as.numeric(gsub(",","",df$i))
}

但是我运行的时候,Rreturns出现如下错误:

> dflist <- c("debt","fundequity","age","coempl","corev")
> for (i in dflist) {
+   df$i <- as.numeric(gsub(",","",df$i))
+ }
Error in `$<-.data.frame`(`*tmp*`, "i", value = numeric(0)) : 
  replacement has 0 rows, data has 570225

我怎样才能让它发挥作用?非常感谢你提前。

编辑:虽然类似于,但输出错误不同,而且我需要覆盖我的变量。在建议的解决方案(见下文)之后,问题似乎出在 $ 符号上。

您无法访问带有 df$ii 为变量的每一列。 您可以像这样使用 apply 系列:

df[,dflist] = apply(df[,dflist],2,function(x) as.numeric(gsub(",","",x)))

如果你想坚持循环,你可以使用

for (i in dflist){
    df[,i]=as.numeric(gsub(",","",df[,i]))
}