如何根据 R 中的条件切换两列中的值?

How to switch values in two columns based on condition in R?

在下面的示例数据集中,如果“d_code”列中的值开始,我需要将“d_code”列中的值与“c_code”列中的值切换除了“7”和“8”之外的任何东西。

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,

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
)
)

使用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 新列。

这是一个tidyverse解决方案: 感谢 Martin Gal 的更新(见评论):在 [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