1

For example, I have a tibble called "data" where the first column is a UserID and the second column is the UserID for a friend of the user from the first column. So for a user with UserId "1" with n friends, there would be n rows with "1" in the first column and the unique UserId's of his friends in the second column. Below is example code for a list of three users with 5 friends each.

data = cbind(c(rep(0, 5), rep(1,5), rep(2, 5)), seq(from=1,to=15, by=1))

I need to convert this tibble into a list of vectors where I can call data_list[["1"]] and return a vector of the UserID's of "1"'s friends. For example from the above code:

`data_list[["1"]]` returns a vector of length 5 `[6 7 8 9 10]`

Anyone know a method of how to do this?

Sai
  • 11
  • 1
  • 2

1 Answers1

2

As the OP showed a matrix instead of a data.frame, we can convert it to data.frame and then split it to a list of vectors based on the value of first column 'V1'

data1 <- as.data.frame(data)
data_list <- split(data1$V2, data1$V1)
data_list[["1"]]
#[1]  6  7  8  9 10
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    It seems one could actually use `aggregate(data[,2], list(data[, 1]), list)` and avoid coercing the matrix to a data.frame...But your `split` solution seems to be about 10 times faster – 12b345b6b78 Nov 21 '18 at 19:45