从长到宽

From long to wide

我在将 data.frame 从长转换为宽时遇到了一些问题。

我的数据是这样的:

Book  Word     Sentiment
AAA    word1     Fear
AAA    word2     Joy
BBB    word3     Trust
BBB    word4     Joy
CCC    word5     Trust
CCC    word6     Trust

我需要创建这个(考虑到独特情绪的出现次数并避免 'word' 列):

Book    Fear   Trust   Joy
 AAA     1       0      1
 BBB     0       1      1        
 CCC     0       2      0         
   

我正在使用 R。

    library(tidyverse)

# A tibble: 6 x 3
  book   word sentiment
  <chr> <int> <chr>    
1 AAA       1 joy      
2 AAA       2 trust    
3 BBB       3 trust    
4 BBB       4 joy      
5 CCC       5 trust    
6 CCC       6 fear     


spread(df, key = sentiment, 
        value = word, 
        fill = 0)

# A tibble: 3 x 4
  book   fear   joy trust
  <chr> <dbl> <dbl> <dbl>
1 AAA       2     1     0
2 BBB       0     4     3
3 CCC       0     6     5

tidyverse 方法如下所示:

Book <- rep(c("AAA", "BBB", "CCC"), each = 2) 
Word <- paste0("word", 1:6)
Sentiment <- c("Fear", "Joy", "Trust", "Joy", "Trust", "Trust")

df <- data.frame(Book, Word, Sentiment)

df |>
  group_by(Book, Sentiment) |> 
  tally() |> 
  pivot_wider(names_from = Sentiment, values_from = n, values_fill = 0)