1

I have a number of large DFs and I want to loop through them. Instead of binding them together to make a big list I thought I should make a simple vector with their names and look though them, but how can I do this?

For example I have:

DF1 <- data.frame(c("a", "b", "c"),c(TRUE, FALSE, TRUE))
DF2 <- data.frame(c("aa", "bb", "cc"),c(FALSE, FALSE, TRUE))
DF3 <- data.frame(c("aaa", "bbb", "ccc"),c(TRUE, FALSE, FALSE))

MyDFs <- c("DF1", "DF2", "DF3")

for (i in MyDFs) {
    print(nrow(i))
}

but the for loop does not work as R does not recognise them as the DFs, how can I correct this? also is this the best way to do this?

1
  • 2
    Your data.frames should be in a list to begin with. Commented Aug 21, 2014 at 11:48

2 Answers 2

1

Or

 sapply(mget(MyDFs),nrow)
 #DF1 DF2 DF3 
 # 3   3   3 

If you don't want to create a vector MyDFs

 sapply(mget(ls(pattern="DF")), nrow) #should also work
Sign up to request clarification or add additional context in comments.

Comments

0

In your own code, just replace print(nrow(i)) with print(nrow(get(i))), since i is: chr "DF1" etc.

for (i in MyDFs) {
     print(nrow(get(i)))
}
[1] 3
[1] 3
[1] 3

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.