Toni - 10 days ago 6
R Question

# In R: return a data frame from apply to iteratively construct data.frame

An example explains best what I need to do:

``````# dd is a list and has some vars
dd = list()
dd\$var = "some data is in here"

# now I want to add a sub data frame \$new
dd\$new = apply(as.array(seq(1,5)), 1, function(x){

return( data.frame(
a = x,
b = x * 2
))

})

str(dd)

# desired structure #######################

#List of 2
# \$ var: chr "some data is in here"
# \$ new:List of 2
#  ..\$ a: num [1:5] 1 2 3 4 5
#  ..\$ b: num [1:5] 2 4 6 8 10

#### Note: this is NOT what str(dd) actually gives, but what I want dd to look like!
``````

How can I achieve this?

# EDIT

based on the answer marked as correct I could solve it:

``````# dd is a list and has some vars
dd = list()
dd\$var = "some data is in here"

# now I want to add a sub data frame \$new
ret = apply(as.array(seq(1,5)), 1, function(x){

return( data.frame(
a = x,
b = x * 2
))

})

dd\$new = as.list(do.call(rbind, ret))

str(dd)
#List of 2
# \$ var: chr "some data is in here"
# \$ new:List of 2
#  ..\$ a: int [1:5] 1 2 3 4 5
#  ..\$ b: num [1:5] 2 4 6 8 10
``````

# Also

there is no reason at all to downvote my question. The problem is stated in the comments of the code. The code is a working minimal example. I stated the desired answer. If you don't bother to read the code, well, at least don't downvote it!

``````res <- setNames(list(dd[[1]], as.list(do.call(rbind, dd\$new))), names(dd))