【问题标题】:allocate values to a new column based on logical string matching in data.table根据 data.table 中的逻辑字符串匹配将值分配给新列
【发布时间】:2015-08-27 12:02:01
【问题描述】:

我有一个庞大的学生数据集,其中有针对荣誉学生的非标准命名约定。我需要创建/填充一个新列,该列将根据单词“Honours”返回 Y 或 N 进行字符串匹配

目前我的数据看起来像这样,有超过 200,000 名学生

library(data.table)
students<-data.table(Student_ID = c(10001:10005), 
                    Degree= c("Bachelor of Laws", "Honours Degree in Commerce", "Bachelor of Laws (with Honours)", "Bachelor of Nursing with Honours", "Bachelor of Nursing"))

我需要添加第三列,以便在我以数据表方式创建新列“荣誉”后,它将像这样填充:

students<-data.table(Student_ID = c(10001:10005), 
                      Degree= c("Bachelor of Laws", "Honours Degree in Commerce","Bachelor of Laws (with Honours)", "Bachelor of Nursing with Honours", "Bachelor of Nursing"), 
                      Honours = c("N","Y", "Y", "Y","N"))

任何帮助将不胜感激。

另外,通过数据表的方式,我的意思是:

students[,Honours:="N"]

【问题讨论】:

  • 您可以逐步进行以便于阅读:idx &lt;- grepl("honours", students$Degree, ignore.case = TRUE); students[idx, Honours := "Y"]; students[!idx, Honours := "N"]

标签: r string data.table multiple-columns


【解决方案1】:

其实很简单

students[, Honours := c("N", "Y")[grepl("Honours", Degree, fixed = TRUE) + 1L]]

您需要做的就是使用一些正则表达式实现函数(例如grepl)搜索“Honours”(这不是一个真正的表达式,因此您可以使用fixed = TREU 来提高性能),然后执行根据您的发现从c("N", "Y") 的向量子集(TRUE/FALSE 逻辑向量 + 1L 将其转换为1,2 的向量,用于从c("N", "Y") 中减去值)


或者,如果这太难阅读,您可以改用ifelse

students[, Honours := ifelse(grepl("Honours", Degree, fixed = TRUE), "Y", "N")]

当然,如果“Honours”可以出现在不同的大小写变体中,您可以将您的 grepl 呼叫切换为 grepl("Honours", Degree, ignore.case = TRUE)


附言

我会建议坚持使用逻辑向量,因为之后您可以轻松地对其进行操作

例如

students[, Honours := grepl("Honours", Degree, fixed = TRUE)]

现在如果你只想选择“荣誉”的人,你可以这样做

students[(Honours)]
#    Student_ID                           Degree Honours
# 1:      10002       Honours Degree in Commerce    TRUE
# 2:      10003  Bachelor of Laws (with Honours)    TRUE
# 3:      10004 Bachelor of Nursing with Honours    TRUE

或者没有“荣誉”的人

students[!(Honours)]
#    Student_ID              Degree Honours
# 1:      10001    Bachelor of Laws   FALSE
# 2:      10005 Bachelor of Nursing   FALSE

【讨论】:

  • 您还可以使用来自data.table 的更简单的运算符%like%,尽管它只是grepl 的包装器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
相关资源
最近更新 更多