我有以下虚拟数据:
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))
我选择了两种产品-国家/地区组合
sdt <- dt %>% filter((Product == "A" & Country == "AI") | (Product == "B" & Country =="EI"))
我希望看到每种组合的并排数值。我可以用dcast
做到这一点
sdt %>% dcast(Year ~ Product + Country)
是否可以使用tidyr包中的spread
执行此操作
发布于 2014-07-24 17:38:11
一种选择是通过paste
连接“Product”和“Country”列来创建新的“Prod_Count”,使用select
删除这些列,并使用tidyr
中的spread
将“long”重塑为“wide”。
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
中的unite
(来自@beetroot的评论)来避免几个步骤,并像以前一样进行整形。
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
发布于 2019-05-16 17:12:01
使用tidyr版本1.0.0中引入的新函数pivot_wider()
,这可以通过一个函数调用来完成。
pivot_wider()
(对等物:pivot_longer()
)的工作方式类似于spread()
。但是,它提供了其他功能,例如使用多个键/名称列(和/或多个值列)。为此,参数names_from
-that指示从哪一列获取新变量的名称-可能采用多个列名(此处为Product
和Country
)。
library("tidyr")
sdt %>%
pivot_wider(id_cols = Year,
names_from = c(Product, Country)) %>%
head(2)
#> # A tibble: 2 x 3
#> Year A_AI B_EI
#> <int> <dbl> <dbl>
#> 1 1990 -2.08 -0.113
#> 2 1991 -1.02 -0.0546
发布于 2019-10-26 17:15:38
Base R解决方案:
# Concatenate grouping vector:
dt$PC <- paste0(dt$Product, "_", dt$Country)
# Spread the vectors by year:
dt2 <- reshape(dt[,c(!(names(dt) %in% c("Product", "Country")))],
idvar = "Year",
ids = unique(dt$Year),
direction = "wide",
timevar = "PC")
# Remove "value.", from the vector names:
names(dt2) <- gsub("value[.]", "", names(dt2))
数据:
dt <- expand.grid(Year = 1990:2014,
Product = LETTERS[1:8],
Country = paste0(LETTERS, "I"))
dt$value <- rnorm(nrow(dt))
https://stackoverflow.com/questions/24929954
复制相似问题