Forcing a column of lists into a row in a data frame R

Create sample data:

id <- c(12, 32, 42, 42, 52, 52, 67, 67) relationship_id <- c(15,1,59,1,61,6,59,1) sample.data <- data.frame(id,relationship_id) 

For each identifier that appears more than once, combine id_link:

 combo <- aggregate(relationship_id ~ id, data = sample.data, paste, sep=",") table(combo$relationship_id) Error in table(combo$relationship_id) : all arguments must have the same length 

I found out what caused this error:

 class(combo$relationship_id) [1] "list" 

But when I try to force the list vector to a character symbol:

 combo["relationship_id"] <- lapply(combo["relationship_id"], as.character) > head(combo) id relationship_id 1 12 15 2 32 1 3 42 c("59", "1") 4 52 c("61", "6") 5 67 c("59", "1") 

It includes concatenation syntax ... I understand that I can parse the output so that it is useful, but why is this happening? Is there an easier way to clear the output?

+5
source share
1 answer

You are trying to solve the wrong problem. If you really wanted to collapse these values ​​into a single character vector, you should use collapse = "," instead of sep .

 combo <- aggregate(relationship_id ~ id, data = sample.data, paste, collapse=",") table(combo$relationship_id) # # 1 15 59,1 61,6 # 1 1 2 1 
+4
source

Source: https://habr.com/ru/post/1210487/


All Articles