简体   繁体   中英

Using lapply to apply mean function over list of data frame

suppose you have a list of n dataframe, for this case the iris base with two variables Petal.Width and Species, I want to use apply or lapply to calculate the average of the Petal.Width column.

df1 = iris[1:10,4:5]
df2 = iris[11:20,4:5]
...
df15 = iris[141:150,4,5]
df = list(df1,df2,...,df15)

The result that I hope if I only had 2 dataframes would be the following

df = list(df1,df2)
df = list(df1,df2)
mean(df[[1]]$Petal.Width);mean(df[[2]]$Petal.Width)
[1] 0.22
[1] 0.25

Thanks

Define the desired function within the lapply call as follows:

lapply(df, function(x) mean(x$Petal.Width))

You can also streamline the construction of df with this:

df = split(iris[,4:5], cut(seq(1,nrow(iris)),15))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM