Home > Blockchain >  Replace all other values in R
Replace all other values in R

Time:01-08

I have a column including lots of "0" and other values (f.i. 2 or 2,3 etc). Is there any possibility to rename the columns with 0 to "None" and all other values to "others"? I wanted to use fct_recode or fct_collapse but cant figure out how to include all other values. Do you have any idea? I must not be necessarily include the fct_recode function.

Thanks a lot Philipp

I tried to use fct_recode, fct_collapse

CodePudding user response:

Here is a way to do it using mtcars and the vs column as an example:

cars <- mtcars
head(cars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
cars$vs <- ifelse(cars$vs == 0, "none", "other")
head(cars)
                   mpg cyl disp  hp drat    wt  qsec    vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  none  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  none  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61 other  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44 other  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  none  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22 other  0    3    1

Note that R coerces the vs column from numeric to character. But you could do that explicitly first for clarity:

cars$vs <- as.character(cars$vs)

CodePudding user response:

Using dplyr, we can do this on multiple colums as

library(dplyr)
df1 <- df1 %>%
     mutate(across(everything(), ~ case_when(.x == 0 ~ "none", TRUE ~ "other")))

Or in base R

df1[] <- c("other", "none")[1   (df1 == 0)]
  •  Tags:  
  • r
  • Related