Home > Mobile >  Using recode_factor to change three numerical values to names
Using recode_factor to change three numerical values to names

Time:11-14

I have one column of data in a data frame, titled "birds". There are three bird species, that are currently identified as 1, 2, and 3, within the 'birds' column of data. I need to recode this column so that the name of the species is there, not the number. I need to make 1=swallow, 2=warbler, and 3= sparrow.

I've tried using recode_factor, but I haven't gotten it to work. This is what my code looks like now:

recode_factor(num_vec, `1` = "swallow", `2` = "warbler", `3` = "sparrow")

The code runs, but the variables aren't changed in my data frame. thank you!!

CodePudding user response:

To recode a column of your data.frame you have to pass that column to recode_factor and assign it back to your dataframe.

Using some fake random example data:

set.seed(123)

dat <- data.frame(
  birds = sample(1:3, 5, replace = TRUE)
)

library(dplyr, warn = FALSE)

dat
#>   birds
#> 1     3
#> 2     3
#> 3     3
#> 4     2
#> 5     3

dat$birds <- recode_factor(dat$birds, `1` = "swallow", `2` = "warbler", `3` = "sparrow")

dat
#>     birds
#> 1 sparrow
#> 2 sparrow
#> 3 sparrow
#> 4 warbler
#> 5 sparrow
  • Related