简体   繁体   中英

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

beside of doing the code below for any value 2,3,4,5 i'm looking for something more elegant:

  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% . For example, if you want to replace values from column a , b , c and d , you can do:

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 :

cols <- c('a','b','c','d')
df[cols] <- lapply(df[cols], function(x) replace(x, x %in% 2:5, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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