有条件地替换因子值

时间:2015-12-08 03:51:10

标签: r

我需要将另一个变量的值替换为另一个变量,如下所示。我正在惹恼R是如何处理因素的。

# setup example
df1 <- data.frame(v1=c(1, 0, 1, 1),
                  v2=c(1, 1, 1, 1))
df1$v1 <- factor(df1$v1, 
                 levels=c(0, 1),
                 labels=c("0", "1"))

df2 <- data.frame(v3=c(1, NA, NA, 0),
                  v4=c(1, 1, 1, 1))
df2$v3 <- factor(df2$v3, 
                 levels=c(0, 1),
                 labels=c("0", "1"))

# df2$v3
#[1] 1    <NA> <NA> 1   
#Levels: 0 1

# recode NA in df2$v3 to 0 if df1$v1==0
# df2$v3 should end up as 1, 0, NA, 1 and remain a factor

df2$v3 <- ifelse(df1$v1=="0" & is.na(df2$v3), "0", df2$v3)

# df2$v3
#[1] "2" "0" NA  "2"

1 个答案:

答案 0 :(得分:0)

# setup example
df1 <- data.frame(v1=c(1, 0, 1, 0),
                  v2=c(1, 1, 1, 1))
df1$v1 <- factor(df1$v1, 
                 levels=c(0, 1),
                 labels=c("0", "1"))

df2 <- data.frame(v3=c(1, NA, NA, 0),
                  v4=c(1, 1, 1, 1))
df2$v3 <- factor(df2$v3, 
                 levels=c(0, 1),
                 labels=c("0", "1"))
df2$v3[which(df1$v1==0)] <- 0

sapply(df2,class)
#       v3        v4 
# "factor" "numeric"