[英]Aggregate function to create frequency matrix in R
我是這里的菜鳥,所以請不要評判我;)
我想創建一個頻率矩陣,其中列名是作者,行名是具有頻率計數的語言。
我的數據如下所示:
language author
----------------------
ita Goethe
ger Schiller
eng Marx
fr Marx
po Schiller
eng Marx
結果我想要這樣的東西
ita ger eng fr po
----------------------------------------------
Schiller 0 1 0 0 1
Goethe 1 0 0 0 0
Marx 0 0 2 1 0
我嘗試將 aggregate() function 與以下內容一起使用:
df1 <- lapply(df, function(x) type.convert(as.character(x)))
aggregate(. ~ language, df1, sum)
但這似乎不起作用。 我怎樣才能重寫它以獲得第二個表。
非常感謝你。 非常感謝您的幫助。
我認識到您可能正在尋找一個基本版本來確定這一點,但臨時的 tidyverse 方法是:
library(tidyverse)
# creating data
dat <- tribble(~language, ~author,
"ita", "Goethe",
"ger", "Schiller",
"eng", "Marx",
"fr", "Marx",
"po", "Schiller",
"eng", "Marx")
dat %>%
count(language, author) %>%
pivot_wider(names_from = language, values_from = n, values_fill = list(n = 0))
# A tibble: 3 x 6
author eng fr ger ita po
<chr> <int> <int> <int> <int> <int>
1 Marx 2 1 0 0 0
2 Schiller 0 0 1 0 1
3 Goethe 0 0 0 1 0
帶底座 R:
df <- read.table(text = "
language author
ita Goethe
ger Schiller
eng Marx
fr Marx
po Schiller
eng Marx", h = T)
as.data.frame.matrix(table(df$author, df$language))
eng fr ger ita po
Goethe 0 0 0 1 0
Marx 2 1 0 0 0
Schiller 0 0 1 0 1
不過,這會按字母順序對行名和列名進行排序。
使用菲爾的數據,
library(tidyr)
table(dat) %>% data.frame() %>% spread(language, Freq)
# author eng fr ger ita po
#1 Goethe 0 0 0 1 0
#2 Marx 2 1 0 0 0
#3 Schiller 0 0 1 0 1
帶有acast
的選項
library(reshape2)
acast(df, author ~ language, length)
df <- structure(list(language = c("ita", "ger", "eng", "fr", "po",
"eng"), author = c("Goethe", "Schiller", "Marx", "Marx", "Schiller",
"Marx")), class = "data.frame", row.names = c(NA, -6L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.