Home > Software design >  Calculate sd and mean for many data frames in R
Calculate sd and mean for many data frames in R

Time:09-04

I have data frames called bmw_1,bmw_2,....bmw_9 and I want to calculate standard deviation and mean for each data frame but I don’t want to write

mean(bmw_1) mean(bmw_2) mean(bmw_3) ... mean(bmw_9)

many times, so any help please

CodePudding user response:

as mentioned in the comment, best way is to get the data frames into a list so you can apply a function over each.

Get all dfs into a list by name pattern:

ls_bmw <- mget(ls(pattern = "bmw_"))

Then apply the mean.

result <- lapply(ls_bmw, mean)

Difficult to go much further without a data example, but to get the results alongside the data frame name use:

 names(ls_bmw)

... to get a vector of the df names and:

 unlist(result)

... to get a vector of the results. The order of names and results elements will match and you convert that into a single result dataframe.

  • Related