Combine list with vector in R

I have some data like:

num = list() num[[1]] = c(1,2,3) num[[2]] = c(4,5,6,7) name = c("Alex", "Patrick") 

How do I combine it into a data frame that looks like this?

 Alex 1 Alex 2 Alex 3 Patrick 4 Patrick 5 Patrick 6 Patrick 7 

I apologize for what may seem obvious. I searched extensively and did not find an answer, perhaps because I do not know how to describe this query well.

+6
source share
3 answers

Give it a try. The new lengths() function comes in handy here.

 data.frame(name = rep(name, lengths(num)), num = unlist(num)) # name num # 1 Alex 1 # 2 Alex 2 # 3 Alex 3 # 4 Patrick 4 # 5 Patrick 5 # 6 Patrick 6 # 7 Patrick 7 

To understand this a little better, let me break it into pieces from the inside. lengths() indicates the lengths of each item in the list, so we have

 lengths(num) # [1] 3 4 

Now we use this as the times argument to rep() to replicate name elements.

 rep(name, lengths(num)) # [1] "Alex" "Alex" "Alex" "Patrick" "Patrick" "Patrick" "Patrick" 

So, to the first column. For the second column, we just turn num into an atomic vector with unlist() .

 unlist(num) # [1] 1 2 3 4 5 6 7 

Put them together as shown above, and we have a new data frame.

+8
source

Another option:

 data.table::rbindlist(Map(function(x,y) data.frame(name = x, num = y), name, num)) name num 1: Alex 1 2: Alex 2 3: Alex 3 4: Patrick 4 5: Patrick 5 6: Patrick 6 7: Patrick 7 
+3
source

Or we can use stack after setting names to 'num' with the name '

 stack(setNames(num, name))[2:1] # ind values #1 Alex 1 #2 Alex 2 #3 Alex 3 #4 Patrick 4 #5 Patrick 5 #6 Patrick 6 #7 Patrick 7 

Just noticed that this was posted in @ user20650 comments. In this case, we can also do

 library(reshape2) melt(setNames(num, name))[2:1] # L1 value #1 Alex 1 #2 Alex 2 #3 Alex 3 #4 Patrick 4 #5 Patrick 5 #6 Patrick 6 #7 Patrick 7 
+2
source

All Articles