[英]How to switch values in two columns based on condition in R?
在下面的示例數據集中,如果“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
,
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
)
)
這是一個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
使用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
和c_code1
是新的色譜柱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.