以下是我的代码:
Female=(1)
Male=(2)
R <- sapply(list(Female, Male), length)
Distribution = sample(c(Female, Male),
size = 100,
prob = rep(c(0.2, 0.8) / R, R),
replace = TRUE)
summary(Distribution)
Distribution[Distribution == "1"] <- "F"
我现在想用“F”替换所有1,用“M”替换2s。我该怎么做?请帮忙。
答案 0 :(得分:1)
取决于......如果你想使用因素:
dd <- as.factor(Distribution)
levels(dd) <- c('F', 'M')
否则:
Distribution[Distribution == 1] <- "F"
Distribution[Distribution == "2"] <- "M" # now Distribution is a character vector
您也可以使用car :: recode:
library(car)
recode(Distribution, '1="F";2="M"')
您还可以使用命名向量:
v <- c(F = 1, M = 2)
names(v[Distribution])
答案 1 :(得分:0)
我认为你必须先将矢量的类型更改为字符:
Distribution <- as.character(Distribution)
Distribution[Distribution == "1"] <- "F"
Distribution[Distribution == "2"] <- "M"
答案 2 :(得分:0)
使其成为因子变量:
factor(Distribution, levels=1:2, labels=c("F", "M"))