【问题标题】:Mutate a column based on the sum of specific rows from another data frame根据来自另一个数据帧的特定行的总和来改变一列
【发布时间】:2020-02-12 09:25:56
【问题描述】:

我在这里寻求帮助。我有两个数据框,df1 和 df2。我想根据 df2 中特定行的总和向 df1 添加一个额外的列。

Df1 包含站名。 Df2 包含位置、年份和以度为单位的观测值。我想要每个站的度数总和。这些学位应该是每年特定地点的总和。 可以将其想象为“每个站点都应根据给定的位置,每年获得其度数之和”。我希望只编码站名和位置,desired_output 中的年份应该包括 df2 中给出的所有年份。

失败的示例和所需的输出。我更喜欢在 tidyverse 环境中工作。

一切顺利

df1 <- data.frame(station = c("station_A", "station_B"))

df2 <- data.frame(location= c("south", "north", "north", "east", "west"), year = c(2000, 2000, 2001, 2001, 2001), degrees = c(5,3,9,5,2))

degrees_for_each_station <-
  df1%>% 
  mutate (degrees = case_when(
    station == "station_A" ~ if_else(df2$location %in% c("north","south"),
                                            sum(df2$degrees),
                                            NA),
    station == "station_B" ~ if_else(df2$location %in% c("north","east", "west"),
                                            sum(df2$degrees),
                                            NA)))

desired_output <- data.frame(station = c("station_A", "station_A","station_B", "station_B"),
                             year = c(2000, 2001, 2000, 2001),
                             degrees = c(8,9,3,16))```


【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一种方法是:

    library(tidyverse)
    
    df1 %>%
      left_join(
        df2 %>%
          mutate(
            location = case_when(
              location == 'south' ~ 'station_A',
              location %in% c('east', 'west') ~ 'station_B',
              location == 'north' ~ 'station_A, station_B'
              )
          ) %>%
          separate_rows(location, sep = ', ') %>%
          group_by(location, year) %>%
          summarise(degrees = sum(degrees)),
        by = c('station' = 'location')
      )
    

    输出:

        station year degrees
    1 station_A 2000       8
    2 station_A 2001       9
    3 station_B 2000       3
    4 station_B 2001      16
    

    【讨论】:

    • 好像我做了一个过于简单的例子。它绝对适用于我的示例,但是,我希望有一个解决方案,我可以告诉 R 每个站点应该从哪些位置求和。在我的真实数据集中,每个站点都有大量的位置来求和,在这个例子中,当在两个或多个站点中找到一些位置时就会出现问题。
    • 但是这个例子真的很好,它也适用于我的数据,我只需要写很多代码。现在,我有一个简短的站点列表,其中包含许多要汇总的位置,这将是每个位置的一行代码,我希望每个站点都有一行代码(请参阅顶部的失败示例) .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2018-11-05
    • 1970-01-01
    相关资源
    最近更新 更多