计算列表列表中每个数据框架的平均值,并将其分配给R中的新向量

发布于 2025-01-23 05:57:53 字数 531 浏览 0 评论 0原文

这是我的数据:

df1 <- data.frame(x = 1:5, y = letters[1:5])
df2 <- data.frame(x = 1:15, y = letters[1:15])
df3 <- data.frame(x = 1:25, y = letters[1:25])
df4 <- data.frame(x = 1:6, y = letters[1:6])
df5 <- data.frame(x = 1:8, y = letters[1:8])

l1 <- list(df1, df2)
l2 <- list(df3, df4, df5)
mylist <- list(l1, l2)

我想计算MyList内所有数据帧中X列的平均值,然后将它们放入新的空列表(或向量)中,例如:

mean_vec <- c(
 mean(df1$x),
 mean(df2$x),
 mean(df3$x),
 mean(df4$x),
 mean(df5$x)
)

This is my data:

df1 <- data.frame(x = 1:5, y = letters[1:5])
df2 <- data.frame(x = 1:15, y = letters[1:15])
df3 <- data.frame(x = 1:25, y = letters[1:25])
df4 <- data.frame(x = 1:6, y = letters[1:6])
df5 <- data.frame(x = 1:8, y = letters[1:8])

l1 <- list(df1, df2)
l2 <- list(df3, df4, df5)
mylist <- list(l1, l2)

I want to calculate the mean of the x column in all data frames inside mylist, and put them in a new empty list (or vector), like so:

mean_vec <- c(
 mean(df1$x),
 mean(df2$x),
 mean(df3$x),
 mean(df4$x),
 mean(df5$x)
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

基于purrr :: map_depth的另一个可能的解决方案:

library(tidyverse)

map_depth(mylist, 2, ~ mean(.x$x)) %>% unlist

#> [1]  3.0  8.0 13.0  3.5  4.5

或使用rrapply :: rrapply,现在较短的解决方案,感谢 @Maël的评论,我感谢谁:

library(rrapply)
library(magrittr)

rrapply(mylist, condition = is.numeric, f = mean, how = "unlist") %>% unname

#> [1]  3.0  8.0 13.0  3.5  4.5

Another possible solution, based on purrr::map_depth:

library(tidyverse)

map_depth(mylist, 2, ~ mean(.x$x)) %>% unlist

#> [1]  3.0  8.0 13.0  3.5  4.5

Or using rrapply::rrapply, solution that is now shorter thanks to @Maël's comment, to whom I thank:

library(rrapply)
library(magrittr)

rrapply(mylist, condition = is.numeric, f = mean, how = "unlist") %>% unname

#> [1]  3.0  8.0 13.0  3.5  4.5
ゃ人海孤独症 2025-01-30 05:57:53

您可以UNLIST您的嵌套列表,并为每个列表计算:

mean_vec <- sapply(unlist(mylist, recursive = F), function(dat) mean(dat$x))

mean_vec
# [1]  3.0  8.0 13.0  3.5  4.5

rapply的另一个选项:

mean <- rapply(mylist, mean)
unname(mean[names(mean) == "x"])
# [1]  3.0  8.0 13.0  3.5  4.5

You can unlist your nested list and compute the mean for each:

mean_vec <- sapply(unlist(mylist, recursive = F), function(dat) mean(dat$x))

mean_vec
# [1]  3.0  8.0 13.0  3.5  4.5

Another option with rapply:

mean <- rapply(mylist, mean)
unname(mean[names(mean) == "x"])
# [1]  3.0  8.0 13.0  3.5  4.5
内心激荡 2025-01-30 05:57:53

purrr解决方案

library(purrr)
library(dplyr)

mylist %>%
  map_depth(., 2, ~ .x %>% summarise(mean = mean(x, na.rm = T))) %>%
  bind_rows() %>%
  pull()

A purrr solution

library(purrr)
library(dplyr)

mylist %>%
  map_depth(., 2, ~ .x %>% summarise(mean = mean(x, na.rm = T))) %>%
  bind_rows() %>%
  pull()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文