lapply函数来计算列表内数据帧的均值 [英] lapply function to compute means of data frames inside a list

查看:137
本文介绍了lapply函数来计算列表内数据帧的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用lapply函数来计算列表内数据帧的均值.

I am trying to compute means of data frames inside a list using lapply function.

df_list <- list(cars, mtcars)
sapply(df_list, mean)

上面的代码似乎无效.但是,当我将其更改为:

The above code doesn't seem to work. However when i changed it to:

 df_list <- c(cars, mtcars)
 sapply(df_list, mean)

输出具有两个数据帧的所有变量的均值.

The output had the means of all the variables of both data frames.

有一种方法可以使用第一种方法来计算均值.

is there a way to compute the means using the first approach.

推荐答案

使用purrr库来实现这一目标……要简单得多:

use the purrr library to achieve this...much simpler:

library(purrr) 
map(df_list, ~map_if(., is.numeric, mean))

如果您希望返回df,则:

If you want a df to be returned then:

map_df(df_list, ~map_if(., is.numeric, mean)) 

答案来自此处: 为什么map_if()在列表中不起作用 应归功于@Axeman

answer is from here: why does map_if() not work within a list credit should go to @Axeman

这篇关于lapply函数来计算列表内数据帧的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆