Home > Software engineering >  How can i replace multiple value in specific column with R
How can i replace multiple value in specific column with R

Time:07-02

i'm try toreplace values (numerical) in specific column with specific text related with condition

for example : if i have this date frame " test " contians from only one column

  test<-data.frame(x=1:9)


test$x[test$x<4] <- "good"
test$x[test$x>4&test$x<7] <- "very good"
test$x[test$x>7] <- "excellent"

View(test)

i need to repalce with :

the valuses leess than 4 with "good"

and valuses between than 4 and 7 with " very good"

and valuses more than 7 " excellent "

  • i try this code in big number but the result isn't what i looking for its show me unstable values

  • i supposed i see in this column just text from " good to excellent" but also shows me a numbers !?

is there any another code working fine or i did someting wrong ?

CodePudding user response:

You can use case_when from dplyr:

library(dplyr)

test<-data.frame(x=1:9)

test %>% 
  mutate(x = 
    case_when(
      x < 4 ~ "good",
      x >= 4 & x < 7 ~ "very good",
      x >= 7 ~ "excellent"
    )
  )
#>           x
#> 1      good
#> 2      good
#> 3      good
#> 4 very good
#> 5 very good
#> 6 very good
#> 7 excellent
#> 8 excellent
#> 9 excellent
  •  Tags:  
  • r
  • Related