【问题标题】:Is there a way to calculate the mean of several dataframes with one for loop and then put it into a dataframe?有没有办法用一个 for 循环计算多个数据帧的平均值,然后将其放入数据帧中?
【发布时间】:2021-05-05 11:51:53
【问题描述】:

所以你可能会注意到我对 R 比较陌生,我似乎真的无法弄清楚这一点。 目前我正在尝试这个:

#定义数据框 概览

#trying 通过我用我需要的所有数据帧制作的列表来选择数据帧 平均值 = for (i in list.dfs) { #计算数据框第二列的平均值(我总是想计算第二列)
均值(i[,2]) } )

由于某种原因,它不会从我选择的信息中创建一列。

【问题讨论】:

标签: r dataframe for-loop


【解决方案1】:

你可以试试sapply/lapply

result <- sapply(list.dfs, function(x) mean(x[[2]]))

【讨论】:

    【解决方案2】:

    我们可以在 tidyverse 中做到这一点

    library(dplyr)
    library(purrr)
    result <- map_dbl(list.dfs, ~ .x %>% 
                                    pull(2) %>%
                                    mean)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多