Replacing Particular Numbers in Dataframe in R with character strings -


i in need of replacing particular values in numeric vector in r. have data frame following.

x1 = 1:20    x2 = c(letters[1:20])    df = data.frame(x1, x2)  df <- df[sample(nrow(df)),] df    x1 x2 1  2  b 2  18 r 3  16 p 4  7  g 5  3  c 6  1  7  14 n 8  10 j 9  8  h 10 11 k 11 17 q 12 6  f 13 15 o 14 13 m 15 19 s 16 5  e 17 4  d 18 9  19 12 l 20 20 t 

in particular data frame need of particular numeric values in x1 character strings such 1:5 = c("w"), 6:10 = c("x"), 11:15 = c("y"), , 16:20 = c("z"). data frame above follows:

   x1 x2 1  w  b 2  z  r 3  z  p 4  x  g 5  w  c 6  w  7  y  n 8  x  j 9  x  h 10 y  k 11 z  q 12 x  f 13 y  o 14 y  m 15 z  s 16 w  e 17 w  d 18 x  19 y  l 20 z  t 

thank you!

we can use findinterval

df$x1 <-  with(df, findinterval(x1, c(1, 6, 11, 16))) df$x1 #[1] 1 4 4 2 1 1 3 2 2 3 4 2 3 3 4 1 1 2 3 4 

note: returns expected output showed in op's post.

based on new output

v1 <- setnames(1:4, c("w", "x", "y", "z")) df$x1 <- names(v1[with(df, findinterval(x1, c(1, 6, 11, 16)))]) df$x1 #[1] "w" "z" "z" "x" "w" "w" "y" "x" "x" "y" "z" "x" "y" "y" "z" "w" "w" "x" "y" "z" 

Comments