R - 对多个数据帧使用for循环进行测试 [英] R - Using a for loop with a test for multiple data frames
问题描述
$ b $我有麻烦1)调用一个变量名的数据框和2)使用逻辑测试跳过。
例如,我用一个数字创建了3个数据框,并且我想添加一个是该值的平方根的列。如果会导致错误,我想跳过数据框。
以下是我到目前为止:
数据帧(a = c(6))
df3 < - data.frame(a = c(1))data_frame(a = c(1))
df2< -3))
df_lst $ b < -
for(df_lst in c(df1,df2,df3){
ifelse(is.na df_lst $ a)= T,skip,
df_list $ b < - sqrt(df1 $ a)
})
在上面的例子中,我希望看到 df1
和 df2
,用列 a
的平方根的新列 b
,然后< c $ c> df3 。
任何帮助都会非常感谢,谢谢大家!
如果你需要对所有的数据进行处理,只是有一堆数据框架放在不同的名字里通常不是一个好主意。将它们存储在一个列表中。例如
mydfs <-list(df1,df2,df3)
然后ÿ你可以使用 lapply
等来处理这些data.frames。例如
mydfs <-lapply(mydfs,function(x){
$ p $ (df_lst in c(p
if(all(x $ a> 0)){
x $ b< -sqrt(x $ a)
}
x;
})
),否则将你的代码改为
df1,df2,df3)){
df< -get(df_lst)
if(all(df $ a> = 0)){
df $ b< - sqrt(df $ a)
}
assign(df_lst,df)
}
也应该可以工作,这通常不被认为是好的做法。
In R, I'm trying to use a for loop, with a nested test, in order to append a column to multiple data frames.
I am having trouble 1) calling a data frame with a variable name and 2) using a logical test to skip.
For example, I created 3 data frames with a number, and I want to add a column that's the squared root of the value. I want to skip the data frame if it'll result in an error.
Below is what I've gotten to so far:
df1 <- data.frame(a=c(1)) df2 <- data.frame(a=c(6)) df3 <- data.frame(a=c(-3)) df_lst$b<- for(df_lst in c("df1","df2","df3"){ ifelse(is.na(df_lst$a) = T, skip, df_list$b <- sqrt(df1$a) })
In the above example, I would ideally like to see
df1
anddf2
with a new columnb
with the squared root of columna
, and then nothing happens todf3
.Any help would be GREATLY appreciated, thank you everyone!
解决方案It's generally not a good idea to just have a bunch of data.frames lying around with different names if you need to do things to all of them. You're better off storing them in a list. For example
mydfs<-list(df1, df2, df3)
Then you can use
lapply
and such to work with those data.frames. For examplemydfs<-lapply(mydfs, function(x) { if(all(x$a>0)) { x$b<-sqrt(x$a) } x; })
Otherwise, changing your code to
for(df_lst in c("df1","df2","df3")) { df<-get(df_lst) if( all(df$a>=0) ) { df$b <- sqrt(df$a) } assign(df_lst, df) }
should work as well, it's just generally not considered good practice.
这篇关于R - 对多个数据帧使用for循环进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!