为频率计数的每个唯一项(字)创建新列

时间:2018-05-10 13:05:21

标签: r

我对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

我如何实现这一目标?

示例dput:

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))

3 个答案:

答案 0 :(得分:3)

我们可以做到以下几点:

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)

答案 1 :(得分: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

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

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)

答案 2 :(得分:1)

您可以从unnest_tokens

中选择tidytext
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

请注意:我喜欢这本书,如果您对整洁文本分析感兴趣,请阅读:https://www.tidytextmining.com/tidytext.html