我需要用另一個變量替換一個變量的值,如下所示。我被絆倒在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"
嘗試,'ifelse(DF1 $ V1 = = 「0」 &is.na(DF2 $ V3), 「0」,as.character(DF2 $ V3))' –
感謝,@ RonakShah,但我需要變量保持一個因子。 –
您可以稍後將其轉換爲因子,也許'as.factor(ifelse(df1 $ v1 ==「0」&is.na(df2 $ v3),「0」,as.character(df2 $ v3)))' –