我是个新手,所以请不要对我评头论足;)
我想创建一个频率矩阵,其中列名是作者,行名是具有频率计数的语言。
我的数据如下所示:
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()函数,如下所示:
df1 <- lapply(df, function(x) type.convert(as.character(x)))
aggregate(. ~ language, df1, sum)但它似乎不起作用。我如何重写它来获得第二个表。
提前谢谢你!非常感谢您的帮助。
发布于 2020-07-31 14:05:10
利用菲尔的数据
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发布于 2020-07-31 13:55:04
我知道您可能正在寻找一个基础版本来确定这一点,但即刻,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发布于 2020-07-31 13:58:18
使用基数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这将按字母顺序对行名和列名称进行排序。
https://stackoverflow.com/questions/63185871
复制相似问题