0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.