简体   繁体   English

Pivot 在 R 中更宽,具有多列

[英]Pivot wider in R with multiple columns

I am having trouble converting a particular dataset from long to wide.我在将特定数据集从长转换为宽时遇到问题。

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

As you can see, some IDs have multiple observations for "animal" and so I want to make multiple columns like this:如您所见,某些 ID 对“动物”有多个观察结果,因此我想制作多个这样的列:

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

Any help is appreciated!任何帮助表示赞赏!

Try this solution.试试这个解决方案。
Most of the work was creating an separate ID column and then creating the unique names for the columns.大部分工作是创建一个单独的 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