【问题标题】:reshaping data from long to wide format un R [duplicate]将数据从长格式重塑为宽格式un R [重复]
【发布时间】:2020-10-23 01:42:18
【问题描述】:

我正在寻找一种方法来重塑我的数据:

> test
      policyID startYear   product
1: G000246-000      2014 Product 1
2: G000246-000      2014 Product 2
3: G000246-000      2014 Product 3
4: G000246-000      2015 Product 1
5: G000246-000      2015 Product 2
6: G000246-000      2015 Product 3

到这里:

     policyID       2014         2015
1: G000246-000    Product 1    Product 1
2: G000246-000    Product 2    Product 2
3: G000246-000    Product 3    Product 3

我试过了:

  reshape(test, idvar = "policyID", timevar = "startYear", direction = "wide")

但我明白了:

      policyID product.2014 product.2015
1: G000246-000    Product 1    Product 1

达到我想要的结果的最佳方法是什么?

数据:

structure(list(policyID = c("G000246-000", "G000246-000", "G000246-000", 
"G000246-000", "G000246-000", "G000246-000"), startYear = c(2014, 
2014, 2014, 2015, 2015, 2015), product = c("Product 1", "Product 2", 
"Product 3", "Product 1", "Product 2", "Product 3")), row.names = c(NA, 
-6L), class = c("data.table", "data.frame"))

【问题讨论】:

  • 既然您使用data.table,请尝试dcast(test, policyID + rowid(startYear) ~ startYear)。在您的数据中,您缺少一个唯一标识符。
  • @markus startyear 被修改为别的东西

标签: r dplyr data.table reshape tidyr


【解决方案1】:

tidyr 解决方案虽然会因为数据集中没有唯一标识符而获得警告消息,但会是

library(tidyr)

test %>% 
  pivot_wider(policyID, names_from = startYear, values_from = product) %>%
  unnest(starts_with("2"))   # or unnest(everything()) ; it depends on which are your other columns

# A tibble: 3 x 3
#   policyID    `2014`    `2015`   
#   <chr>       <chr>     <chr>    
# 1 G000246-000 Product 1 Product 1
# 2 G000246-000 Product 2 Product 2
# 3 G000246-000 Product 3 Product 3

【讨论】:

  • 不幸的是,这不会产生任何结果:'另外:警告消息:product 中的值不是唯一标识的;输出将包含列表列。 * 使用values_fn = list(product = list) 抑制此警告。 * 使用values_fn = list(product = length) 确定重复出现的位置 * 使用values_fn = list(product = summary_fun) 总结重复'
  • 使用您在问题开头提供的test 示例数据(没有.internal.selfref 参数),我获得了答案中显示的输出。我的tidyr 版本是1.1.0 和R 4.0.0。也许他们和你的不一样。此外,我指定您会收到一条警告消息,因为您的数据集中没有唯一标识符,因此出现警告消息是正常的。
【解决方案2】:

非常类似于markus的评论:

test[, dcast(.SD, policyID + product ~ startYear, value.var = "product")
     ][, !"product"]

      policyID      2014      2015
1: G000246-000 Product 1 Product 1
2: G000246-000 Product 2 Product 2
3: G000246-000 Product 3 Product 3

数据

test <- data.table(
  policyID = c("G000246-000"), 
  startYear = rep(c(2014,2015), each = 3), 
  product = paste("Product", 1:3)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2015-08-04
    • 2021-09-15
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多