Home > Enterprise >  Is there a way to convert integers in a column to character in R?
Is there a way to convert integers in a column to character in R?

Time:09-23

I have a data frame which has different clinical variables for patients who either had a heart failure or not?

I have a column as gender with values 0 and 1, 0 corresponding to females and 1 corresponding to males?

My question is

How can I get my data frame column from this

gender 
1
1
0
1
0
0

to this...

gender
Female 
Male 
Male
Female 
Male 
Female 
Female 

Is there a way to convert the integers 0, 1 to text "Female" and "Male"

CodePudding user response:

We can pass a replacement vector after converting to index by adding 1 to it. In R, the indexing starts from 1, and thus by adding 1 to 0, 1, the values are changed to 1 and 2 respectively which can be used as a position index for replacement

df1$gender <- c("Female", "Male")[df1$gender   1]

CodePudding user response:

ifelse() could work like this:

df <- data.frame(gender = c(1,0,1,0,3))

df$gender2 <- ifelse(df$gender == 1, "Male", "Female")
df
#>   gender gender2
#> 1      1    Male
#> 2      0  Female
#> 3      1    Male
#> 4      0  Female
#> 5      3  Female

You can also stack multiple conditions:

df$gender3 <- ifelse(df$gender == 1, "Male", 
                     ifelse(df$gender == 0, "Female", NA))
df
#>   gender gender2 gender3
#> 1      1    Male    Male
#> 2      0  Female  Female
#> 3      1    Male    Male
#> 4      0  Female  Female
#> 5      3  Female    <NA>
  • Related