[英]replace values in a column into Data Frame with another value (same for all)
My data frame consists of 21 columns, for this problem only one is relevant: I want replace values 2 or 3 or 4 or 5 in a column a with the value 1 (in the same column).我的数据框由 21 列组成,对于这个问题只有一列是相关的:我想将 a 列中的值 2 或 3 或 4 或 5 替换为值 1(在同一列中)。
beside of doing the code below for any value 2,3,4,5 i'm looking for something more elegant:除了为任何值 2、3、4、5 执行下面的代码之外,我正在寻找更优雅的东西:
df <- df %>% mutate (a = replace(a, a == 2,1))
df <- df %>% mutate (a = replace(a, a == 3,1))
df <- df %>% mutate (a = replace(a, a == 4,1))
df <- df %>% mutate (a = replace(a, a == 5,1))
so i'm just stock with the condition "or" i need create inside the code... any solution?所以我只知道条件“或”我需要在代码中创建...任何解决方案?
You can replace multiple columns using across
and multiple values with %in%
.您可以使用
across
和多个值替换多个列%in%
。 For example, if you want to replace values from column a
, b
, c
and d
, you can do:例如,如果要替换列
a
、 b
、 c
和d
中的值,您可以执行以下操作:
library(dplyr)
df <- df %>% mutate(across(a:d, ~replace(., . %in% 2:5, 1)))
#For dplyr < 1.0.0 use `mutate_at`
#df <- df %>% mutate_at(vars(a:d), ~replace(., . %in% 2:5, 1))
In base R, you can do this with lapply
:在基数 R 中,您可以使用
lapply
执行此操作:
cols <- c('a','b','c','d')
df[cols] <- lapply(df[cols], function(x) replace(x, x %in% 2:5, 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.