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.
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.
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.
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.
unlist() function in R Language is used to convert a list to vector.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With