63

我有以下虚拟数据:

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)

是否可以spreadtidyr包中做到这一点?

4

3 回答 3

61

一种选择是通过加入 'Product' 和 'Country' 列来创建一个新的 'Prod_Count',使用frompaste删除这些列select并从 'long' 重塑为 'wide' 。spreadtidyr

 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

unite或者我们可以通过使用from tidyr(来自@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
于 2014-07-24T09:38:11.370 回答
10

使用 tidyr 版本 1.0.0 中引入的新功能pivot_wider(),这可以通过一个函数调用来完成。

pivot_wider()(counterpart: pivot_longer()) 与spread(). 但是,它提供了额外的功能,例如使用多个键/名称列(和/或多个值列)。为此,names_from表示新变量名称取自哪一列的参数可能会采用多个列名(此处为ProductCountry)。

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

另见:https ://tidyr.tidyverse.org/articles/pivot.html

于 2019-05-16T09:12:01.303 回答
0

基础 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))
于 2019-10-26T09:15:38.430 回答