【问题标题】:Replace negative values in a row based on conditions with grouping and conditions in R用R中的分组和条件根据条件替换一行中的负值
【发布时间】:2021-08-31 11:20:33
【问题描述】:

我有一个这样的数据框,

Industry = c("Industry1", "Industry1", "Industry1", "Industry2", "Industry2", "Industry3")
calc = c(-1.2345, 67890, 45678, -9.86544, 32456, 56789)
cy = c(0, 2019, 2017, 2016, 0, 2015)
py = c(0, 2018, 2016, 2015, 0, 2014)

data = data.frame(Industry, calc, cy, py, stringsAsFactors = FALSE)

当 cy = 0 和 py = 0 时,我想通过根据行业分组计算 calc 列的平均值来替换 calc 列中的负值。我尝试了以下方法,

data = data %>% 
  group_by("Industry") %>% 
  mutate(calc = ifelse(cy == 0 & py == 0, summarise(calc = mean(calc)), calc))

但这不起作用。谁能帮我解决这个问题?

【问题讨论】:

  • 您的data 显示此错误Error in data.frame(Industry, calc, cy, py, stringsAsFactors = FALSE) : arguments imply differing number of rows: 6, 7
  • 我已经改正了!

标签: r if-statement dplyr conditional-statements


【解决方案1】:

你也可以使用replace

Industry = c("Industry1", "Industry1", "Industry1", "Industry2", "Industry2", "Industry3")
calc = c(-1.2345, 67890, 45678, -9.86544, 32456, 56789)
cy = c(0, 2019, 2017, 2016, 0, 2015)
py = c(0, 2018, 2016, 2015, 0, 2014)

data = data.frame(Industry, calc, cy, py, stringsAsFactors = FALSE)
library(tidyverse)

data %>% group_by(Industry) %>%
  mutate(calc = replace(calc, calc <0 & cy == 0 & py == 0, mean(calc[calc >= 0])))
#> # A tibble: 6 x 4
#> # Groups:   Industry [3]
#>   Industry      calc    cy    py
#>   <chr>        <dbl> <dbl> <dbl>
#> 1 Industry1 56784        0     0
#> 2 Industry1 67890     2019  2018
#> 3 Industry1 45678     2017  2016
#> 4 Industry2    -9.87  2016  2015
#> 5 Industry2 32456        0     0
#> 6 Industry3 56789     2015  2014

reprex package (v2.0.0) 于 2021-06-17 创建

【讨论】:

    【解决方案2】:

    你可以直接变异,不用summarise()

    data %>% 
      group_by(Industry) %>% 
      mutate(
        calc = if_else(calc < 0 & cy == 0 & py == 0, mean(calc[calc > 0]), calc)
      ) %>%
      ungroup()
    
    # # A tibble: 6 x 4
    #   Industry      calc    cy    py
    #   <chr>        <dbl> <dbl> <dbl>
    # 1 Industry1 56784        0     0
    # 2 Industry1 67890     2019  2018
    # 3 Industry1 45678     2017  2016
    # 4 Industry2    -9.87  2016  2015
    # 5 Industry2 32456        0     0
    # 6 Industry3 56789     2015  2014
    

    【讨论】:

    • 这种应用均值的方式包括这样的均值计算。例如,让我们考虑 Industry1,计算是这样的 (-1.2345+67890+45678)/3 = 37856。相反,我想在计算平均值时排除 calc 中的 py = 0 和 cy = 0 值,像这样 (67890 + 45678)/2 = 56784。是否可以使用 R 来做到这一点?
    • 是的,您可以在计算平均值之前对calc[calc &gt; 0] 进行子集化。我已经更新了答案。
    • 好的,只要再添加一个条件就可以了!谢谢 Zaw!
    猜你喜欢
    • 2020-04-24
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多