首页 > 解决方案 > 根据现有的字符向量在 R 数据框中创建新的字符列

问题描述

我是 R 新手,并且被困在看似简单的任务上 - 在 R 数据框中创建新的列向量,条件是现有的字符向量。

例如,我有一个数据框“class”,其中包含一个字符列(“Names”)和一个数字列(“Student_numbers”):

Names <- c("Sarah", "Mary", "Ben", "Will", "Alex") 
Student_numbers <- c(3,5,6,7,7)
class <- data.frame(Names, Student_numbers) 

在数据框“class”中,我想添加一个名为“Gender”的新字符列,它基于字符向量“Names”中的值:

Male <- c("Ben", "Will", "Alex") 
Female <- c("Sarah", "Mary") 

 Names    Student_numbers  Gender
1 Sarah   3                Female
2 Mary    5                Female
3 Ben     6                Male
4 Will    7                Male
5 Alex    7                Male

我不想手动执行此操作,而是希望根据上面定义的字符向量自动执行此操作。

预先感谢您的帮助。

标签: r

解决方案


你可以ifelse在这里使用:

class$Gender <- ifelse(class$Names %in% Male, 
                       "Male", 
                       ifelse(class$Names %in% Female, "Female", NA))
class
#   Names Student_numbers Gender
# 1 Sarah               3 Female
# 2  Mary               5 Female
# 3   Ben               6   Male
# 4  Will               7   Male
# 5  Alex               7   Male

如果您有更多案例,您也可以使用 case_whenfrom dplyr

library(dplyr)
case_when(class$Student_numbers < 4 ~ "Grp1",
          class$Student_numbers < 6 ~ "Grp2",
          class$Student_numbers < 7 ~ "Grp3",
          TRUE                      ~ "Other")

推荐阅读