英文:
Combine Two Variables Into One Based on their Values in R
问题
我尝试从同一数据框(df)的两个变量中创建一个新变量,就像下面这样。这些类别是相互排斥的。
VAR1 VAR2
1 1
2 2
6 6
1 = 是
2 = 否
6 = 未答
我尝试用以下脚本来获取组合变量,但它不起作用:
if (df$VAR1 == 1) {
df$combo = 1
} else if (df$VAR2 == 1) {
df$combo = 2
} else if ((df$VAR1 == 2) & (df$VAR2 == 2)) {
df$combo = 3
} else if ((df$VAR1 == 6) & (df$VAR2 == 6)) {
df$combo = 6
}
任何指导将不胜感激。
英文:
I am trying to create a new variable out of two variables in the same dataframe (df), like those below. The categories are mutually exclusive.
VAR1 VAR2
1 1
2 2
6 6
1 = yes
2 = no
6 = did not answer
The script I have tried to get the combined variable, but is not working is below:
if (df$VAR1 == 1) {
df$combo = 1
} else if (df$VAR2 == 1) {
df$combo = 2
} else if ((df$VAR1 == 2) & (df$VAR2 == 2)) {
df$combo = 3
} else if ((df$VAR1 == 6) & (df$VAR2 == 6)) {
df$combo = 6
}
Any pointers will be appreciated.
答案1
得分: 1
你可以尝试以下两种方法来完成此任务:
使用传统的R代码:
for (i in 1:nrow(df)){
if (df$VAR1[i] == 1) {
df$combo[i] = 1
} else if (df$VAR2[i] == 1) {
df$combo[i] = 2
} else if ((df$VAR1[i] == 2) & (df$VAR2[i] == 2)) {
df$combo[i] = 3
} else if ((df$VAR1[i] == 6) & (df$VAR2[i] == 6)) {
df$combo[i] = 6
}
}
或者使用 dplyr
包:
library(dplyr)
df %>%
mutate(combo = case_when(
VAR1 == 1 ~ 1,
VAR2 == 1 ~ 2,
(VAR1 == 2 & VAR2 == 2) ~ 3,
(VAR1 == 6 & VAR2 == 6) ~ 6,
TRUE ~ NA_real_
))
英文:
You may try
for (i in 1:nrow(df)){
if (df$VAR1[i] == 1) {
df$combo[i] = 1
} else if (df$VAR2[i] == 1) {
df$combo[i] = 2
} else if ((df$VAR1[i] == 2) & (df$VAR2[i] == 2)) {
df$combo[i] = 3
} else if ((df$VAR1[i] == 6) & (df$VAR2[i] == 6)) {
df$combo[i] = 6
}
}
VAR1 VAR2 combo
1 1 1 1
2 2 2 3
3 6 6 6
Or use dplyr
library(dplyr)
df %>%
mutate(combo = case_when(
VAR1 == 1 ~ 1,
VAR2 == 1 ~ 2,
(VAR1 == 2 & VAR2 == 2) ~ 3,
(VAR1 == 6 & VAR2 == 6) ~ 6,
TRUE ~ NA_real_
))
VAR1 VAR2 combo
1 1 1 1
2 2 2 3
3 6 6 6
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论