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

use*_*000 5 r data-manipulation

在下面的示例数据集中,如果“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")
Run Code Online (Sandbox Code Playgroud)

所需的输出如下所示:

 sum     d_code    c_code 
  98     "7300"    "1200"   
  73     "8300"    "1500"   
  62     "8400"    "1050"
Run Code Online (Sandbox Code Playgroud)

Par*_*ark 4

使用基地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  
Run Code Online (Sandbox Code Playgroud)

或者

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
)
)
Run Code Online (Sandbox Code Playgroud)