简体   繁体   English

R-将for循环用于测试多个数据帧

[英]R - Using a for loop with a test for multiple data frames

In R, I'm trying to use a for loop, with a nested test, in order to append a column to multiple data frames. 在R中,我试图使用带有嵌套测试的for循环,以便将一列附加到多个数据帧。

I am having trouble 1) calling a data frame with a variable name and 2) using a logical test to skip. 我遇到麻烦1)调用带有变量名的数据框,以及2)使用逻辑测试跳过。

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. 例如,我创建了3个带有数字的数据框,并且我想添加一列作为值的平方根。 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 and df2 with a new column b with the squared root of column a , and then nothing happens to df3 . 在上面的示例中,理想情况下,我希望看到df1df2的新列b的列a平方根为a ,然后df3没有任何反应。

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) mydfs <-列表(df1,df2,df3)

Then you can use lapply and such to work with those data.frames. 然后,您可以使用lapply等来处理这些data.frames。 For example 例如

mydfs<-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. 应该也可以正常工作,这通常不被认为是好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM