繁体   English   中英

Pivot 在 R 中更宽,具有多列

[英]Pivot wider in R with multiple columns

我在将特定数据集从长转换为宽时遇到问题。

col1           col2
ID             55.
animal.        dog
animal         bear
animal         rabbit
shape.         circle
ID             67.
animal.        cat
shape.         square

如您所见,某些 ID 对“动物”有多个观察结果,因此我想制作多个这样的列:

ID.   animal.  animal2 animal3  shape
55.    dog       bear.  rabbit  circle
67.    cat.      NA     NA      square

任何帮助表示赞赏!

试试这个解决方案。
大部分工作是创建一个单独的 ID 列,然后为这些列创建唯一名称。

library(tidyr)
library(dplyr)
library(vctrs)

df<- structure(list(col1 = c("ID", "animal.", "animal", "animal", "shape.", "ID", "animal.", "shape."), 
                  col2 = c("55.", "dog", "bear", "rabbit", "circle", "67.", "cat", "square")), 
               class = "data.frame", row.names = c(NA, -8L))
   
#create the ID column
df$ID <- NA
#find the ID rows
idrows <- which(df$col1 == "ID")
#fill column and delete rows
df$ID[idrows] <- df$col2[idrows]
df <- fill(df, ID, .direction = "down")
df <- df[-idrows, ]

#create unique names in each grouping and the pivot wider
df %>% group_by(ID) %>% 
       mutate(col1= vec_as_names(col1, repair = "unique")) %>% 
       ungroup() %>% 
       pivot_wider(id_cols = "ID", names_from = "col1", values_from = "col2")



  ID    animal. animal...2 animal...3 shape.
  <chr> <chr>   <chr>      <chr>      <chr> 
1 55.   dog     bear       rabbit     circle
2 67.   cat     NA         NA         square

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM