我有一些不同日子吃的食物数据。
day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)
我想在x轴上创建一个食物,在y轴上创建一个日子,以及在矩阵中每天食物的数量
food.list <- unique(all$food)
day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
1 2 3
pizza 2 0 2
taco 1 2 2
snake 1 1 1
解决此问题的简单方法是什么?
答案 0 :(得分:3)
library(reshape2)
dcast(data = all, formula = food~day, fun.aggregate = length, value.var = "food")
food 1 2 3
1 pizza 2 0 2
2 snake 1 1 1
3 taco 1 2 2
OR
table(all$food, all$day)
1 2 3
pizza 2 0 2
snake 1 1 1
taco 1 2 2
答案 1 :(得分:2)
将日,食物和数量留在不同的栏目中会更“整洁”。 注意:我在创建数据框时添加了stringsAsFactors = FALSE
,以避免以后出现问题。
library(dplyr)
all %>%
group_by(day, food) %>%
tally()
但如果你真的想要几天作为专栏,那么你总是可以spread
:
library(tidyr)
all %>%
group_by(day, food) %>%
tally() %>%
spread(day, n)
# A tibble: 3 × 4
food `1` `2` `3`
* <chr> <int> <int> <int>
1 pizza 2 NA 2
2 snake 1 1 1
3 taco 1 2 2
如果您希望NA为0,请添加:
%>%
mutate_if(is.integer, funs(replace(., is.na(.), 0)))
答案 2 :(得分:2)
抱歉,table
出了什么问题?
day = c(1,1,1,1,2,2,2,3,3,3,3,3)
food = c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
table(food, day)
day
food 1 2 3
pizza 2 0 2
snake 1 1 1
taco 1 2 2
答案 3 :(得分:1)
您也可以使用xtabs
:
xtabs(col~food+day, cbind(all, col=1))
# OR
xtabs(col~food+day, transform(all, col=1))
# OR
xtabs(~food+day, all) # thanks to user20650
# day
#food 1 2 3
# pizza 2 0 2
# snake 1 1 1
# taco 1 2 2