替换数据框列表中的值 [英] Replacing values in a list of data frames
问题描述
我有一个数据帧列表.每个都有一个ID列,然后是许多数字列(带有列名).
I have a list of data frames. Each has an ID column, followed by a number of numeric columns (with column names).
我想将所有数字列的所有1替换为0,但将ID列保持不变.我可以使用
I would like to replace all the 1's with 0's for all the numeric columns, but keep the ID column the same. I can do this in part with a single data frame using
df[,-1] <- 0
但是当我尝试将其嵌入lapply时,它失败了:
But when I try to embed this in lapply, it fails:
df2 <- lapply(df, function(x) {x[,-1] <- 0})
我试过使用子集ifelse进行变异,但是在这种简单的替换方法上苦苦挣扎.可以从头开始重新创建数据帧,或者在末尾重新组合ID列,但这使我感到震惊,因为这应该很容易...
I've tried using subset, ifelse, while, mutate, but struggling with this simple replacement. Could recreate the data frames from scratch, or recombine the ID column at the end, but this strikes me as something that should be easy...
测试列表:
test_list <- list(data.frame("ID"=letters[1:3], "col2"=1:3, "col3"=0:2), data.frame("ID"=letters[4:6], "col2"=4:6, "col3"=0:2))
最终结果应该是:
final_list <- list(data.frame("ID"=letters[1:3], "col2"=0, "col3"=0), data.frame("ID"=letters[4:6], "col2"=0, "col3"=0))
推荐答案
将 return(x)
添加到您的函数中,然后它应该可以正常工作.
Add return(x)
to your function and then it should work fine.
lapply(test_list, function(x){
x[, -1] <- 0
return(x)
})
# [[1]]
# ID col2 col3
# 1 a 0 0
# 2 b 0 0
# 3 c 0 0
#
# [[2]]
# ID col2 col3
# 1 d 0 0
# 2 e 0 0
# 3 f 0 0
这篇关于替换数据框列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!