简体   繁体   English

使用lapply将均值函数应用于数据帧列表

[英]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.

相关问题 使用lapply()函数查找R中数据帧中每一行的均值 - Using lapply()-function to find the mean of every row in data frame in R 如何使用lapply将函数应用于数据框的列? - How can I apply a function to a column of a data frame using lapply? 使用 lapply 对数据框列表应用函数并将输出保存到具有不同名称的文件 - Using lapply to apply a function over list of data frames and saving output to files with different names 在列表上使用 lapply 并添加带有数据框名称的列 - Using lapply over a list and adding a column with data frame name 在数据框中使用 lapply/apply 查找子集 - find a subset using lapply/apply in a data frame 使用lapply将功能应用于文件的读入列表并将输出另存为新文件列表 - Using lapply to apply a function over read-in list of files and saving output as new list of files 在R中,在正在处理数据帧列表的lapply中使用函数apply() - In R, use a function apply() inside of lapply that is working over a list of data frames R:使用lapply创建新列和值,并在data.frame列表中应用嵌套,输出错误 - R:create new column and value using lapply & apply nested on data.frame list, wrong output 使用 lapply 对数据框列表进行分组 - Using lapply over a list of data frames with grouping 将stargazer与通过对拆分data.frame进行重叠处理而创建的lm对象列表一起使用 - Using stargazer with a list of lm objects created by lapply-ing over a split data.frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM