r - 根据现有的字符向量在 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
我不想手动执行此操作,而是希望根据上面定义的字符向量自动执行此操作。
预先感谢您的帮助。
解决方案
你可以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
from dplyr
:
library(dplyr)
case_when(class$Student_numbers < 4 ~ "Grp1",
class$Student_numbers < 6 ~ "Grp2",
class$Student_numbers < 7 ~ "Grp3",
TRUE ~ "Other")
推荐阅读
- javascript - 如何使用类名定位页面上的所有元素并将其高度四舍五入为 32 的倍数?
- javascript - lodash.throttle - 没有调用节流方法?
- python - AttributeError:模块“pptx.chart”没有属性“数据”
- reactjs - 将状态从子组件传递到父组件中包含的另一个子组件
- javascript - Vue中的动态条件轮播项目选择
- java - 为什么我的 JOptionPane 消息对话框在控制台窗口后面弹出?
- imagemagick - Imagemagick 透明度在 6.9 中不起作用,但在 7.0 中起作用
- reactjs - 此电子邮件已存在验证
- html - 如何使用 getElementBy 提取表单字段而不存在任何属性标签
- bash - 提示用户确认