【问题标题】:How to switch values in two columns based on condition in R?如何根据R中的条件切换两列中的值?
【发布时间】:2021-12-15 22:37:26
【问题描述】:

在下面的示例数据集中,如果“d_code”列中的值不是以“7”和“8”开头,我需要将“d_code”列中的值与“c_code”列中的值进行切换。

sample_df <- tibble::tribble(
  ~sum, ~d_code, ~c_code, 
  98,     "1200",    "7300",   
  73,     "1500",    "8300",   
  62,     "8400",    "1050")

所需的输出如下所示:

 sum     d_code    c_code 
  98     "7300"    "1200"   
  73     "8300"    "1500"   
  62     "8400"    "1050"

【问题讨论】:

    标签: r data-manipulation


    【解决方案1】:

    使用基础R

    sample_df[!(substr(sample_df$d_code,1,1) %in% c(7,8)), c("d_code", "c_code") ] <- sample_df[!(substr(sample_df$d_code,1,1) %in% c(7,8)), c("c_code", "d_code") ]
    sample_df
    
        sum d_code c_code
      <dbl> <chr>  <chr> 
    1    98 7300   1200  
    2    73 8300   1500  
    3    62 8400   1050  
    

    transform(sample_df, d_code = ifelse(
      !(substr(sample_df$d_code,1,1) %in% c(7,8)),
      c_code,
      d_code
    ),
    c_code = ifelse(
      !(substr(sample_df$d_code,1,1) %in% c(7,8)),
      d_code,
      c_code
    )
    )
    

    【讨论】:

    • 我喜欢这个逻辑,但我认为如果将!(substr(sample_df$d_code,1,1) %in% c(7,8)) 保存到一个临时变量中会更好地阅读,这样就不必重复冗长的选择。
    【解决方案2】:

    这是一个tidyverse 解决方案: 感谢 Martin Gal 更新(见 cmets):在 [7,8] 中删除了 ,

    library(dplyr)
    library(stringr)
    
    sample_df %>% 
      mutate(across(ends_with("code"), ~ifelse(str_detect(.,"^[78]"), d_code, c_code)))
    
        sum d_code c_code
      <dbl> <chr>  <chr> 
    1    98 7300   1200  
    2    73 8300   1500  
    3    62 8400   1050  
    

    【讨论】:

    • [7,8] 我认为, 不属于那里。
    • 马丁很好,所以[78] 应该这样做?!
    【解决方案3】:

    使用ifelse

    sample_df$d_code1 = ifelse(sample_df$d_code > 2000, sample_df$d_code, sample_df$c_code)
    sample_df$c_code1 = ifelse(sample_df$c_code > 7000, sample_df$d_code, sample_df$c_code)
    

    d_code1c_code1 新列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 2021-01-26
      • 2020-04-24
      • 2021-08-16
      • 2019-08-03
      • 1970-01-01
      • 2017-09-17
      • 2018-01-15
      相关资源
      最近更新 更多