R pivot_wider 保持每行一个 id [英] R pivot_wider to keep one id per row

查看:42
本文介绍了R pivot_wider 保持每行一个 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 ID 和值的数据集,其中一个 ID 可以采用多个值.目前,同一个 ID 在有多个值时会按行重复,但我希望每行保留一个 ID,必要时添加更多列.这是一个可重现的示例:

I have a dataset with IDs and Value where one ID could take multiple values. Currently, the same ID is repeated row-wise when it has multiple values, but I hope to keep one ID per row, adding more columns when necessary. Here's a reproducible example:

df <- data.frame(id = c(1,1,1,2,3,3),
                 val = c(10:15))

我想要的是

df2 <- data.frame(id = c(1:3),
                  val1 = c(10, 13, 14),
                  val2 = c(11, "", 15), 
                  val3 = c(12, "", ""))

我尝试使用 pivot_wider 完成它,如下所示,但它有两个问题:(1) 不知道如何创建我自己的列名;(2) 想添加列,但它在单元格内创建了一个列表.

I've tried to get it done using pivot_wider as below but it had two problems: (1) couldn't figure out how to create a column name of my own; (2) wanted to add columns but it creates a list within a cell.

library(tidyr)
df %>% pivot_wider(values_from = val, values_fn = list, names_prefix = "x")

推荐答案

需要添加序列列:

df %>% group_by(id) %>%
  mutate(time=row_number()) %>%
  pivot_wider(names_from=time, values_from = val, names_prefix = "val")

# A tibble: 3 x 4
# Groups:   id [3]
     id  val1  val2  val3
  <dbl> <int> <int> <int>
1     1    10    11    12
2     2    13    NA    NA
3     3    14    15    NA


library(tidyr)
library(dplyr)

这篇关于R pivot_wider 保持每行一个 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆