Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine list with vector in R

Tags:

r

I have some data like the following:

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'm sorry for posting what's likely an obvious question. I've searched extensively and not found the answer, probably because I don't know how to describe this query well.

like image 844
Alex Lach Avatar asked Jun 03 '16 20:06

Alex Lach


People also ask

How do I add a list to a vector in R?

To convert a list to a vector in R use unlist() function. This function takes a list as one of the arguments and returns a Vector.

How do I combine lists in R?

R provided two inbuilt functions named c() and append() to combine two or more lists. c() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.

How do I extract an element from a list in R?

The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list. The [[ operator can also use named indices so that you don't have to remember the exact ordering of every element of the list. You can also use the $ operator to extract elements by name.

How do I convert something to a vector in R?

unlist() function in R Language is used to convert a list to vector.


2 Answers

Give this 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's break it into parts from the inside out. lengths() tells us the lengths of each element in a list, so we have

lengths(num)
# [1] 3 4

Now we use that as the times argument in rep() to replicate the elements of name.

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

So that's 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 these together as shown above and we have your new data frame.

like image 162
Rich Scriven Avatar answered Sep 18 '22 00:09

Rich Scriven


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
like image 42
Psidom Avatar answered Sep 20 '22 00:09

Psidom