【问题标题】:counting specific words across multiple columns in R计算 R 中多列中的特定单词
【发布时间】:2017-11-01 08:04:26
【问题描述】:

我有一个这样的数据框

df <- data.frame(id=c(1, 2, 3, 4, 5), staple_1=c("potato", "cassava","rice","fruit","coffee"), staple_2=c("cassava","beer","peanuts","rice","yams"), staple_3=c("rice","peanuts","fruit","fruit","rice"))

我也有这样的字符向量

staples<-c("potato","cassava","rice","yams")

我想创建一个新变量,它是“staples”字符向量中任何单词出现的行总和。结果应该是这样的

df$staples<-c(3,1,1,1,2)

我尝试了几种方法,但到目前为止没有任何效果。我的实际数据框要大得多,字符向量中有 20 个或更多单词。我确信有一个简单的解决方案,但我以某种方式错过了它。

【问题讨论】:

  • 请发表您的方法

标签: r string vector character tidyverse


【解决方案1】:

一个简单的apply 就可以了。

apply(df, 1, function(x) sum(staples %in% x))
#[1] 3 1 1 1 2

df$staples <- apply(df, 1, function(x) sum(staples %in% x))

【讨论】:

    【解决方案2】:

    这是一个 tidyverse 解决方案。

    library(tidyverse)
    
    df <- data_frame(id = c(1, 2, 3, 4, 5), 
                 staple_1 = c("potato", "cassava", "rice", "fruit", "coffee"), 
                 staple_2 = c("cassava", "beer", "peanuts", "rice", "yams"), 
                 staple_3 = c("rice", "peanuts", "fruit", "fruit", "rice"))
    
    staples_vect <- c("potato", "cassava", "rice", "yams")
    
    df %>% 
         mutate(staples = pmap_int(select(., starts_with("staple_")), ~sum(c(...) %in% staples_vect)))
    

    在使用 dplyr 时,最好避免对全局变量和数据框中的列使用相同的名称。

    【讨论】:

      【解决方案3】:

      另一种方法是遍历列,使用%in% 创建逻辑vectors 的list 并添加(+)和Reduce

      Reduce(`+`, lapply(df[-1], `%in%`, staples))
      #[1] 3 1 1 1 2
      

      或使用rowSums,通过将数据集转换为matrix(不带“id”列),使用%in% 转换为逻辑vector,分配dim 以转换为与维度相同的维度的df[-1] 并获得rowSums

      rowSums(`dim<-`(as.matrix(df[-1]) %in% staples, dim(df[-1])))
      #[1] 3 1 1 1 2
      

      【讨论】:

        猜你喜欢
        • 2019-04-19
        • 2020-10-04
        • 2016-03-01
        • 2019-02-12
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        相关资源
        最近更新 更多