Reputation: 1241
i have a list of 10 data frames with names as q1,q2,q3....q9,q10. all these data frames are of same structure with two columns: "word" and "count". Now i want to print the first 5 rows' values. I also want to print the iteration count of the for loop. But when i'm running the following for-loop, i'm getting an error as Error in nam[["word"]] : Subscript out of bounds
for(x in 1:10){
for(y in 1:5){
nam<-paste("q",x,sep = "")
print(nam[["word"]][y])
print(nam[["count"]][y])
print(y)
}}
And when i change my code for addressing my data frames like this, i get the error as Error in nam$word : $ operator is invalid for atomic vectors
for(x in 1:10){
for(y in 1:5){
nam<-paste("q",x,sep = "")
print(nam2$word[y])
print(nam2$count[y])
print(y)
}}
Please suggest how i can avoid/overcome this error. Any help is appreciated. Thanks, Aman
Upvotes: 1
Views: 1386
Reputation: 214927
Since nam
is just a character here, you need to use get
function to get the actual data.frame first:
for(x in 1:10){
for(y in 1:5){
nam<-paste("q",x,sep = "")
print(get(nam)[["word"]][y])
print(get(nam)[["count"]][y])
print(y)
}}
Another way to accomplish what you want to see which avoids for loop:
lapply(1:10, function(i) head(get(paste0("q", i)), 5))
Or:
lapply(mget(paste0("q", 1:10)), head, 5)
Upvotes: 2