[英]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. 假设您有一个n个数据帧的列表,对于这种情况,虹膜基数具有两个变量Petal.Width和Species,我想使用apply或lapply来计算Petal.Width列的平均值。
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 我希望如果只有2个数据帧的结果如下
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
调用中定义所需的函数,如下所示:
lapply(df, function(x) mean(x$Petal.Width))
You can also streamline the construction of df
with this: 您还可以使用以下方法简化df
的构建:
df = split(iris[,4:5], cut(seq(1,nrow(iris)),15))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.