kaix
kaix

Reputation: 305

Applying a loop to a few dataframes

I have 10 different data frames which are named df1,df2,df3,... df10. I would like to find the mean for all column for all 10 of the data frames. I have tried this code but there was and error "Error in df[j] : object of type 'closure' is not subsettable" . Is there a better way to do it?

for (j in 1:10) {
mean[j] <- apply(df[j][,2:57], 2 , mean , na.rm=TRUE)
}

Upvotes: 0

Views: 47

Answers (3)

DPH
DPH

Reputation: 4344

an option would be the purrr package:

library(purrr)
# some dummy df 1
df1 <- data.frame(col1 = c(1,2,3,4),
                  col2 = c(5,6,7,8))
# some dummy df 1
df2 <- data.frame(col1 = c(1,2,3,4),
                  col2 = c(5,6,7,8))
# bind it to a list
l <- list(df1, df2)
# map colmeans over the list object
purrr::map(l, function(x) colMeans(x))

[[1]]
col1 col2 
 2.5  6.5 

[[2]]
col1 col2 
 2.5  6.5 

Upvotes: 0

Karthik S
Karthik S

Reputation: 11596

Using nested sapply:

df1 <- data.frame(c1 = 1:5, c2 = 4:8)
df2 <- data.frame(c1 = 6:10, c2 = 9:13)
df3 <- data.frame(c1 = 1:5, c2 = 8:12)
mylist <- list(df1,df2,df3)
mylist
[[1]]
  c1 c2
1  1  4
2  2  5
3  3  6
4  4  7
5  5  8

[[2]]
  c1 c2
1  6  9
2  7 10
3  8 11
4  9 12
5 10 13

[[3]]
  c1 c2
1  1  8
2  2  9
3  3 10
4  4 11
5  5 12


sapply(mylist, function(x) sapply(x, mean))
   [,1] [,2] [,3]
c1    3    8    3
c2    6   11   10

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

Get the dataframes in a list and use colMeans to get means of the columns.

result <- lapply(mget(paste0('df', 1:10)), function(x) colMeans(x[, 2:57], na.rm = TRUE))

Upvotes: 1

Related Questions