Reputation: 57
I want to change 0 to Male and 1 to Female in only 1 column of my data set.
Sex Age LHUM RHUM LRAD
0 40-50 0 1 0
1 50+ 1 1 1
0 30-50 0 0 1
0 25-30 0 0 0
1 50+ 0 0 0
1 30-40 0 0 0
0 30-50 0 0 0
Upvotes: 2
Views: 2884
Reputation: 23014
The plyr
package has a function mapvalues
for making such replacements:
library(plyr)
df1$Sex <- mapvalues(df1$Sex, from = c(0,1), to = c("Male", "Female"))
Upvotes: 1
Reputation: 887038
You can try
df1$Sex <- c('Male', 'Female')[df1$Sex +1L]
df1$Sex
#[1] "Male" "Female" "Male" "Male" "Female" "Female" "Male"
Or
df1$Sex <- as.vector(factor(df1$Sex, labels=c('Male', 'Female')))
If the values are 0 and -1
df1$Sex <- c('Male', 'Female')[ (-1*(df1$Sex))+1L]
df1 <- structure(list(Sex = c(0L, 1L, 0L, 0L, 1L, 1L, 0L),
Age = c("40-50",
"50+", "30-50", "25-30", "50+", "30-40", "30-50"), LHUM = c(0L,
1L, 0L, 0L, 0L, 0L, 0L), RHUM = c(1L, 1L, 0L, 0L, 0L, 0L, 0L),
LRAD = c(0L, 1L, 1L, 0L, 0L, 0L, 0L)), .Names = c("Sex",
"Age", "LHUM", "RHUM", "LRAD"), class = "data.frame",
row.names = c(NA, -7L))
Upvotes: 2