根据现有字符向量在R数据框中创建新的字符列

时间:2019-09-20 14:20:55

标签: r

我对R并不陌生,并且执着于一项看似简单的任务-在R数据帧中以现有字符向量为条件创建新的列向量。

例如,我有一个数据框“ class”,其中有一个字符列(“名称”)和一个数字列(“ 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

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

在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您可以在此处使用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_when中的dplyr

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

答案 1 :(得分:0)

此解决方案使用Tidyverse库进行工作:

library(tidyverse)
Names <- c("Sarah", "Mary", "Ben", "Will", "Alex") 
Student_numbers <- c(3,5,6,7,7)
class <- data.frame(Names, Student_numbers)
class
class <- class %>% mutate(gender = ifelse(Names %in% c("Sarah","Mary"),"Female","Male"))
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

希望有帮助。

添加:考虑您的其他示例,让我们来看一下:

df <- data.frame(dogs = c("Chucho","Pulgas","Pirata","Carcas","Fido","Bigotes"), 
         number_id = c("10","12","15","16","30","19"), stringsAsFactors = FALSE)

df <- df %>% mutate(dog_type = ifelse(dogs %in% c("Chucho","Pulgas"),"Chihuahua",
                           ifelse(dogs %in% c("Pirata","Carcas"),"Hairless Chimu","San Bernardo"))) %>% mutate(dog_size = ifelse(dog_type %in% c("Chihuahua","Hairless Chimu"),"Small","Big"))

   dogs      number_id   dog_type          dog_size
1  Chucho        10      Chihuahua         Small
2  Pulgas        12      Chihuahua         Small
3  Pirata        15      Hairless Chimu    Small
4  Carcas        16      Hairless Chimu    Small
5  Fido          30      San Bernardo      Big
6  Bigotes       19      San Bernardo      Big

希望我回答了您的其他问题。

此致

亚历克西斯

答案 2 :(得分:0)

您还可以使用sapply和更熟悉的if

class$gender <- sapply(class$Names, function(x) if(x %in% Male) "Male" else "Female" )

 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

我还建议您在创建stringAsFactors=FALSE时添加class,以避免不得不处理factors