我有一个包含许多列的数据框,但是我想创建另一个仅包含种族和配偶列的数据框。我有这个数据样本。
gender name race realm spouse
1 Female Adanel Men Gondor Not Married
2 Male Lagduf Orc Mordor Married
2 Male Boromir Men Gondor Married
我想创建一个带有种族和配偶(生物已“结婚”)的数据框,以便可以从中绘制一个图表,显示种族之间的婚姻差异。在新数据框中应该出现的唯一数据是以下数据:
race spouse
1 Orc Married
2 Men Married
我希望让种族和配偶(其中的生物是“已婚”)分列。我已经尝试过这样的事情:
marriedCreatures <- data %>% filter(spouse == "Married" & race)
由于我最近开始使用R,所以我不知道应该如何从其他数据框的列创建这个新数据框。
如果有人可以帮助我,我将不胜感激。
谢谢!
答案 0 :(得分:1)
df <- data.frame(
gender = c("Female", "Male", "Male"),
name = c("Adanel", "Lagduf", "Boromir"),
race = c("Men", "Orc", "Men"),
spouse = c("Not married", "Married", "Married")
)
library(dplyr)
# base R
marriedCreatures <- df[df$spouse == "Married", c("race", "spouse")]
marriedCreatures
# dplyr
marriedCreatures <- df %>%
dplyr::filter(spouse == "Married") %>%
dplyr::select(race, spouse)
marriedCreatures
如果更喜欢dplyr版本,但单线也应该不错:-)
答案 1 :(得分:1)
带有base R
subset(df, spouse == "Married", select = c("race", "spouse"))