Home > database >  Replace numbers with strings in multiple columns, R
Replace numbers with strings in multiple columns, R

Time:12-17

I have several columns in which certain numbers correspond with different values. I would like to replace them only in the first 3 columns.

A1   A2   A3   A4   A5
1    3    NA    5   2
1    2    1     2   1
3    NA   NA    1   8
2    1    NA    1   12
1=cat
2=dog
3=rabbit

so I would like the output to be:

A1       A2       A3     A4     A5
cat     rabbit    NA     5      2
cat     dog       cat    2      1
rabbit  NA        NA     1      8
dog     cat       NA     1      12

I know how to replace the numbers in individual columns, but I would like to learn an easier way to do many at once. Thank you!

CodePudding user response:

Using dplyr:

Code:

df %>% 
  mutate(across(1:3,
                ~ case_when(
                  . == 1 ~ "cat",
                  . == 2 ~ "dog",
                  . == 3 ~ "rabbit",
                  TRUE ~ NA_character_
                )))

Output:

       A1     A2     A3    A4    A5
   <char> <char> <char> <int> <int>
1:    cat rabbit   <NA>     5     2
2:    cat    dog    cat     2     1
3: rabbit   <NA>   <NA>     1     8
4:    dog    cat   <NA>     1    12

Data:

df <- structure(list(A1 = c(1L, 1L, 3L, 2L), A2 = c(3L, 2L, NA, 1L), 
    A3 = c(NA, 1L, NA, NA), A4 = c(5L, 2L, 1L, 1L), A5 = c(2L, 
    1L, 8L, 12L)), row.names = c(NA, -4L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x00000222c4081ef0>)

CodePudding user response:

In base R, if the values are numeric, then use the values as index for replacing

df[1:3] <- c("cat", "dog", "rabbit")[as.matrix(df[1:3])]

-output

> df
      A1     A2   A3 A4 A5
1    cat rabbit <NA>  5  2
2    cat    dog  cat  2  1
3 rabbit   <NA> <NA>  1  8
4    dog    cat <NA>  1 12

data

df <- structure(list(A1 = c(1L, 1L, 3L, 2L), A2 = c(3L, 2L, NA, 1L), 
    A3 = c(NA, 1L, NA, NA), A4 = c(5L, 2L, 1L, 1L), A5 = c(2L, 
    1L, 8L, 12L)), class = "data.frame", row.names = c(NA, -4L
))
  •  Tags:  
  • r
  • Related