我的数据集中有两个变量,我想将college_grad
和sex
组合起来创建sex_grad
。水平应如下:
我该如何解决这个问题。我知道如何使用mutate
和ifelse
,但只创建了两个变量。
编辑:
collegegrad
有两个级别:
sex
有两个级别:
答案 0 :(得分:0)
使用paste
代替ifelse
。
college_grad = c("Graduate", "Non-graduate")
sex = c("Male", "Female")
df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- with(df, paste(sex, college_grad))
df
# college_grad sex sex_grad
# 1 Graduate Male Male Graduate
# 2 Non-graduate Male Male Non-graduate
# 3 Graduate Female Female Graduate
# 4 Non-graduate Female Female Non-graduate
修改:这个对应于您的修改。
college_grad = c("Yes", "No")
sex = c("Male", "Female")
df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- with(df, ifelse(college_grad == "Yes", paste(sex, "Graduate"), paste(sex, "Non-graduate")))
df
答案 1 :(得分:0)
通过组合你可能意味着一些事情。如果没有要使用的数据集以及您想要的输出示例,则回答您的问题会更难。
如果要将列添加到一起,并保留所有现有列,则:
library(tidyverse)
mtcars %>%
mutate(
mpg_am = mpg + am
)
如果您要删除现有列,请将mutate
替换为transmute
。
如果要将变量收集到列中,则:
mtcars %>%
rownames_to_column("car_names") %>%
gather(variable, obs, -car_names)
答案 2 :(得分:0)
您也可以使用interaction
。使用@ hpesoj626的示例数据:
college_grad <- c("Graduate", "Non-graduate")
sex <- c("Male", "Female")
df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- interaction(df$sex, df$college_grad, sep = ' & ')
结果:
> df
college_grad sex sex_grad
1 Graduate Male Male & Graduate
2 Non-graduate Male Male & Non-graduate
3 Graduate Female Female & Graduate
4 Non-graduate Female Female & Non-graduate