我有一个如下所示的数据框:
Df <- data.frame(
mn = c(1,0,1,1,1,1,0),
bc = c(1,1,1,0,0,1,1),
bn = c(0,0,1,1,0,1,0))
我想将这些重新编码为一个新变量。
我试过这样的事情
Df$Var[which(Df$mn %in% 1)] <- "mn"
Df$Var[which(Df$bc %in% 1)] <- "bc"
Df$Var[which(Df$bn %in% 1)] <- "bn"
这有效,但我不能获得5个月,5个基点和3个bns。看起来一个命令会覆盖另一个命令。我知道在SPSS中这样的事情是可能的。它自动组合它们。我的问题是如何在没有任何覆盖的情况下做到这一点。
答案 0 :(得分:1)
Df$mn[which(Df$mn %in% 1)] <- "mn"
Df$bc[which(Df$bc %in% 1)] <- "bc"
Df$bn[which(Df$bn %in% 1)] <- "bn"
我相信这就是你想要的。
如果您想要新列:
Df <- data.frame(
mn = c(1,0,1,1,1,1,0),
bc = c(1,1,1,0,0,1,1),
bn = c(0,0,1,1,0,1,0))
Df1<-Df
Df1$mn[which(Df1$mn %in% 1)] <- "mn"
Df1$bc[which(Df1$bc %in% 1)] <- "bc"
Df1$bn[which(Df1$bn %in% 1)] <- "bn"
Df<-cbind(Df,Df1)
答案 1 :(得分:1)
Df$Var <- apply(Df, 1, function(r) {paste(names(Df)[r == 1], collapse=" ")})
给出
# mn bc bn Var
# 1 1 1 0 mn bc
# 2 0 1 0 bc
# 3 1 1 1 mn bc bn
# 4 1 0 1 mn bn
# 5 1 0 0 mn
# 6 1 1 1 mn bc bn
# 7 0 1 0 bc
答案 2 :(得分:1)
类似于其他没有使用的(),%in%或cbind():
Df <- data.frame(
mn = c(1,0,1,1,1,1,0),
bc = c(1,1,1,0,0,1,1),
bn = c(0,0,1,1,0,1,0))
Df$Var1[Df$mn == 1] <- "mn"
Df$Var2[Df$bc == 1] <- "bc"
Df$Var3[Df$bn == 1] <- "bn"
答案 3 :(得分:0)
DF %>% tidyr::gather("var", "value", 1:3) %>%
dplyr::mutate(var1 = ifelse(value==1, var, " "))
或者
Df %>% dplyr::mutate(mn1 = ifelse(mn==1, "mn", " "),
bc1 = ifelse(bc==1, "bc", " "),
bn1 = ifelse(bn==1, "bn", " "))
> Df
mn bc bn mn1 bc1 bn1
1 1 1 0 mn bc
2 0 1 0 bc
3 1 1 1 mn bc bn
4 1 0 1 mn bn
5 1 0 0 mn
6 1 1 1 mn bc bn
7 0 1 0 bc