【问题标题】:Create new column for each unique item (word) with frequency count [duplicate]使用频率计数为每个唯一项目(单词)创建新列[重复]
【发布时间】:2018-10-20 18:25:06
【问题描述】:

我对 R 和一般编程很陌生,并且一直在努力解决以下问题。

我有一个如下的数据框:

id     animals
 1     cat dog
 2     cat pig dog fish fish
 3     horse horse

我想为每个动物创建一个新列,其中包含每个 id 的频率计数:

id    cat  dog  fish  horse  pig
 1     1    1     0     0     0
 2     1    1     2     0     1
 3     0    0     0     2     0

我如何做到这一点?

示例输入:

structure(list(id = 1:3, animals = structure(1:3, .Label = c("cat dog", 
    "cat pig dog fish fish", "horse horse"), class = "factor")), .Names = c("id", 
    "animals"), class = "data.frame", row.names = c(NA, -3L))

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以做到以下几点:

    df %>%
        separate_rows(animals) %>%
        count(id, animals) %>%
        spread(animals, n, fill = 0)
    ## A tibble: 3 x 6
    #     id   cat   dog  fish horse   pig
    #  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    #1    1.    1.    1.    0.    0.    0.
    #2    2.    1.    1.    2.    0.    1.
    #3    3.    0.    0.    0.    2.    0.
    

    样本数据

    df <- read.table(text =
        "id     animals
     1     'cat dog'
     2     'cat pig dog fish fish'
     3     'horse horse'", header = T)
    

    【讨论】:

    • 你可以使用separate_rows来代替mutate和unnest
    • 确实@kath,谢谢!
    • 并且spread有一个填充选项,可以指定fill = 0
    • 再次正确@kath;这里显然已经太晚了。我应该签字了。
    【解决方案2】:

    data.table 的单行可能是:

    library(data.table)
    dcast(setDT(df)[, unlist(strsplit(as.character(animals), " ")), by = id], id ~  V1)
    
    #  id cat dog fish horse pig
    #1  1   1   1    0     0   0
    #2  2   1   1    2     0   1
    #3  3   0   0    0     2   0
    

    或者作为另一种选择,您可以在reshape2 中使用dcast

    library(reshape2)
    spl <- strsplit(as.character(df$animals), " ")
    df_m <- data.frame(id = rep(df$id, times = lengths(spl)), animals = unlist(spl))
    dcast(df_m, id ~ animals)
    

    【讨论】:

      【解决方案3】:

      你可以从tidytext中选择unnest_tokens

      library(tidyverse)
      library(tidytext)
      
      x %>%  unnest_tokens(word,animals) %>%  table()
      

      数据:

      x <- structure(list(id = 1:3, animals = c("cat dog", "cat pig dog fish fish", 
      "horse horse")), .Names = c("id", "animals"), row.names = c(NA, 
      -3L), class = "data.frame")
      

      输出

         word
      id  cat dog fish horse pig
        1   1   1    0     0   0
        2   1   1    2     0   1
        3   0   0    0     2   0
      

      附注:我喜欢这本书,如果你对 tidytext 分析感兴趣,必读:https://www.tidytextmining.com/tidytext.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2017-11-27
        • 1970-01-01
        相关资源
        最近更新 更多