简体   繁体   English

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

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

In example-dataset below, I need to switch the values in column "d_code" with values in column "c_code", if value in column "d_code" begins with anything but "7" and "8".在下面的示例数据集中,如果“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")

The desired output would look like this:所需的输出如下所示:

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

Using base R ,使用基数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  

or或者

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

Here is a tidyverse solution: update thanks to Martin Gal (see comments): removed , in [7,8]这是一个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  

Using ifelse使用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_code1 and c_code1 the new coloumns. d_code1c_code1是新的色谱柱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM