问题描述
我有以下虚拟数据:
library(dplyr)
library(tidyr)
library(reshape2)
dt <- expand.grid(Year = 1990:2014, Product=LETTERS[1:8], Country = paste0(LETTERS, "I")) %>% select(Product, Country, Year)
dt$value <- rnorm(nrow(dt))
我选择了两种产品-国家/地区组合
I pick two product-country combinations
sdt <- dt %>% filter((Product == "A" & Country == "AI") | (Product == "B" & Country =="EI"))
并且我想并排查看每个组合的值.我可以用 dcast
做到这一点:
and I want to see the values side by side for each combination. I can do this with dcast
:
sdt %>% dcast(Year ~ Product + Country)
是否可以使用 tidyr 包中的 spread
来做到这一点?
Is it possible to do this with spread
from the package tidyr?
推荐答案
一种选择是通过 paste
加入 'Product' 和 'Country' 列来创建一个新的 'Prod_Count',删除那些带有 select
的列,并使用 tidyr
中的 spread
从long"到wide"重新整形.
One option would be to create a new 'Prod_Count' by joining the 'Product' and 'Country' columns by paste
, remove those columns with the select
and reshape from 'long' to 'wide' using spread
from tidyr
.
library(dplyr)
library(tidyr)
sdt %>%
mutate(Prod_Count=paste(Product, Country, sep="_")) %>%
select(-Product, -Country)%>%
spread(Prod_Count, value)%>%
head(2)
# Year A_AI B_EI
#1 1990 0.7878674 0.2486044
#2 1991 0.2343285 -1.1694878
或者我们可以通过使用 tidyr
(来自@beetroot 的评论)中的 unite
来避免几个步骤并像以前一样重塑.
Or we can avoid a couple of steps by using unite
from tidyr
(from @beetroot's comment) and reshape as before.
sdt%>%
unite(Prod_Count, Product,Country) %>%
spread(Prod_Count, value)%>%
head(2)
# Year A_AI B_EI
# 1 1990 0.7878674 0.2486044
# 2 1991 0.2343285 -1.1694878
这篇关于是否可以在类似于 dcast 的 tidyr 中的多列上使用传播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!