【问题标题】:Why numbers not mapped to each row?为什么数字没有映射到每一行?
【发布时间】:2018-10-24 16:50:23
【问题描述】:

所以我试图在另一个数据集中查找每个名称的出现次数。我试图运行的代码是:

Data$Count <- grep(Data$Name,OtherDataSet$LeadName) %>% length()

问题是当我运行它时,名字的数字被映射到该列中的每个位置。为什么会这样?

【问题讨论】:

  • patterngrep 中未矢量化尝试library(stringr); library(dplyr);Data %&gt;% mutate(Count = sum(str_detect(OtherDataSet$LeadName, Name))) 假设'Data' 和'OtherDataSet' 具有相同的行数
  • 我正在遍历LeadName 中的一列它不起作用,因为它们的行数不同
  • 在这种情况下,您可能需要grep(paste0("\\b(", paste(Data$Name, collapse="|"), ")\\b"), OtherDataSet$LeadName)
  • 这是做什么的?
  • akrun 制作了一个使用正则表达式替代符号| 的模式来检查Data$Name 中的任何选项是否出现在LeadName

标签: r dplyr


【解决方案1】:
library(tidyverse)
Data <- data_frame(Name=c("Dog","Cat","Bird"))
OtherDataSet <- data_frame(LeadName=c("Frog","Cat","Catfish","BirdOfPrey","Bird","Bird"))
Data <- Data %>% mutate(Count=map(.x = Name,~str_detect(.,pattern = OtherDataSet$LeadName)) %>% map_int(~sum(.)))

【讨论】:

    猜你喜欢
    • 2016-02-05
    • 2020-01-19
    • 2013-10-07
    • 2023-03-31
    • 1970-01-01
    • 2021-05-13
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多