-1

I have the following data in R:

head(x)
     col1    col2      
[1,] "Id1" "Atr1"
[2,] "Id1" "Atr2"
[3,] "Id1" "Atr3"
[4,] "Id1" "Atr4"
[5,] "Id2" "Atr5"
[6,] "Id2" "Atr6"

I would like to transform x to have a dataframe in this form (with rows of nonequal length)

"Id1" "Atr1" "Atr2" "Atr3" "Atr4"
"Id2" "Atr5" "Atr6"
Marouen
  • 907
  • 3
  • 13
  • 36

2 Answers2

1

Lets make it more generic

xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop
xy.list <- vector("list", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
    xy.list[[i]] <- xy.df[i,]
}

you can do

xy.list <- split(xy.df, seq(nrow(xy.df)))

alternatively

xy.list <- as.list(as.data.frame(t(xy.df)))
Areza
  • 5,623
  • 7
  • 48
  • 79
0

Here is probably what you want. dat is a data frame with NA if there are missing values.

library(tidyverse)

dat <- m %>%
  as_tibble() %>%
  group_by(col1) %>%
  mutate(ID = 1:n()) %>%
  spread(ID, col2) %>%
  ungroup()
dat
# # A tibble: 2 x 5
#   col1  `1`   `2`   `3`   `4`  
#   <chr> <chr> <chr> <chr> <chr>
# 1 Id1   Atr1  Atr2  Atr3  Atr4 
# 2 Id2   Atr5  Atr6  NA    NA   

Data

m <- matrix(c("Id1", "Atr1", "Id1", "Atr2", "Id1", "Atr3", 
              "Id1", "Atr4", "Id2", "Atr5", "Id2", "Atr6"),
            ncol = 2, byrow = TRUE)
colnames(m) <- c("col1", "col2")
www
  • 38,575
  • 12
  • 48
  • 84