【问题标题】:How to calculate mean of column, then paste mean value as row value in another data frame in R?如何计算列的平均值,然后将平均值作为行值粘贴到 R 中的另一个数据框中?
【发布时间】:2021-12-18 22:22:10
【问题描述】:

我有 36 个数据框,每个数据框都包含标题为“lon”、“lat”和“bottom_temp”的列。每个不同的数据框代表 1980 年到 2015 年之间一年的数据。我有一个名为“month3_avg_box”的单独数据框,其中包含两列:“年”和“avg_bottom_temp”。 “month3_avg_box”数据框的年份列包含 1980-2015 年间每一年的一行。我想在我拥有的 36 个数据框中的每一个中找到每个“bottom_temp”列的平均值,并将每个平均值放在我拥有的新“month3_avg_box”数据框的相应行中。我会写一个我想要的小例子:

1980_df:
lon      lat      bottom_temp
-75.61   39.1      11.6
-75.60   39.1      11.5
-75.59   39.1      11.6
-75.58   39.1      11.7

(1980_df = 11.6 的 bottom_temp 列的平均值)

1981_df:
lon      lat      bottom_temp
-75.57   39.1      11.9
-75.56   39.1      11.9
-75.55   39.1      12.0
-75.54   39.1      11.8

(1981_df 的 bottom_temp 列的平均值 = 11.9)

1982_df:
lon      lat      bottom_temp
-75.57   39.1      11.6
-75.56   39.1      11.7
-75.55   39.1      11.9
-75.54   39.1      11.2

(1982_df = 11.6 的 bottom_temp 列的平均值)

现在,我想将这些平均值放入我的“month3_avg_box”数据框中,如下所示:

month3_avg_box:
Year      Avg_bottom_temp
1980        11.6
1981        11.9
1982        11.6

这有意义吗?我该怎么做?

【问题讨论】:

    标签: r average mean


    【解决方案1】:

    我们可以在list 中获取数据集,绑定数据集,从名为list 的名称中创建一个“年份”列,通过mean 进行分组

    library(dplyr)
    library(stringr)
    lst(`1980_df`, `1981_df`, `1982_df`) %>%
        bind_rows(.id = 'Year') %>%
        group_by(Year = str_remove(Year, '_df')) %>%
        summarise(Avg_bottom_temp = mean(bottom_temp))
    

    -输出

    # A tibble: 3 × 2
      Year  Avg_bottom_temp
      <chr>           <dbl>
    1 1980             11.6
    2 1981             11.9
    3 1982             11.6
    

    数据

    `1980_df` <- structure(list(lon = c(-75.61, -75.6, -75.59, -75.58), lat = c(39.1, 
    39.1, 39.1, 39.1), bottom_temp = c(11.6, 11.5, 11.6, 11.7)), class = "data.frame", row.names = c(NA, 
    -4L))
    `1981_df` <- structure(list(lon = c(-75.57, -75.56, -75.55, -75.54), lat = c(39.1, 
    39.1, 39.1, 39.1), bottom_temp = c(11.9, 11.9, 12, 11.8)), class = "data.frame", row.names = c(NA, 
    -4L))
    `1982_df` <- structure(list(lon = c(-75.57, -75.56, -75.55, -75.54), lat = c(39.1, 
    39.1, 39.1, 39.1), bottom_temp = c(11.6, 11.7, 11.9, 11.2)), class = "data.frame", row.names = c(NA, 
    -4L))
    

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2018-09-07
      相关资源
      最近更新 更多