R - 对多个数据帧使用for循环进行测试 [英] R - Using a for loop with a test for multiple data frames

查看:153
本文介绍了R - 对多个数据帧使用for循环进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R,我试图使用for循环,嵌套测试,为了追加到多个数据框的列。
$ 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){
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 and df2 with a new column b with the squared root of column a, and then nothing happens to 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)

Then you can use lapply and such to work with those 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.

这篇关于R - 对多个数据帧使用for循环进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆