如果在 R 时不符合标准,如何保留单元格的原始值?
How to keep original values of cells if they do not meet criterion in case when at R?
我希望所有单元格值都变为 运行(已编辑:在具有多列的 DF 中),如果它不符合 case_when 的任何条件,则保留原始值数据。
例如
突变(~case_when(.==“嗨”~1,
.=="你好"~2,
T~(保持原值)
))
如果您 运行 case_when
仅针对 1 列,您可以在 TRUE ~
中引用列名称本身
library(dplyr)
df %>%
mutate(cyl = case_when(col == 'hi' ~ 1,
col == 'hello' ~ 2,
TRUE ~ col))
如果你是 运行 这对于具有 mutate_at
/across
的多列你可以使用 .
df %>%
mutate(across(c(a, b), ~case_when(.== "hi" ~ 1,
.== "hello"~2,
TRUE ~ .)))
我希望所有单元格值都变为 运行(已编辑:在具有多列的 DF 中),如果它不符合 case_when 的任何条件,则保留原始值数据。 例如 突变(~case_when(.==“嗨”~1, .=="你好"~2, T~(保持原值) ))
如果您 运行 case_when
仅针对 1 列,您可以在 TRUE ~
library(dplyr)
df %>%
mutate(cyl = case_when(col == 'hi' ~ 1,
col == 'hello' ~ 2,
TRUE ~ col))
如果你是 运行 这对于具有 mutate_at
/across
的多列你可以使用 .
df %>%
mutate(across(c(a, b), ~case_when(.== "hi" ~ 1,
.== "hello"~2,
TRUE ~ .)))