0

I have child_sequences as list in R

child = c("a","b","c")

I generate this child sequence over and over again based on some logic using a for loop, let say -

child1 = c("a","b","c")
child2 = c("b","a","c")
child3 = c("a","a","b")

and so on.

I want all this lists to be stored as a dataframe so that I can save it to csv and analyze it later.

How do I do it efficiently in R? How can I keep appending this list to dataframe using the same for loop?

My dataframe should look like -

a , b ,c 
b, a, c
a, a, b
4
  • Those aren't lists you have. Those are vectors. Lists and vectors are different things in R. Commented Jun 22, 2018 at 15:53
  • how do i check if a variable type is list or vector ? Commented Jun 22, 2018 at 15:54
  • You can use is.list() to see if something is a list. But building a data.frame row-by-row in R is one of the most inefficient things you can do in R. It's much better to build the data frame column-by-column. What's the actual scenario you are dealing with. Commented Jun 22, 2018 at 15:56
  • thank you for the help. I am trying to create a data frame from lists. I can convert vector to list in each for loop call. But at the end I am trying to create a dataframe from this list. Commented Jun 22, 2018 at 16:17

2 Answers 2

2

How about:

child1 = c("a","b","c")
child2 = c("b","a","c")
child3 = c("a","a","b")

child_list <- list(child1, child2, child3)

as.data.frame(do.call(rbind, child_list))
  V1 V2 V3
1  a  b  c
2  b  a  c
3  a  a  b
Sign up to request clarification or add additional context in comments.

Comments

0

If there are many objects of the same pattern name, we can use ls (specify the pattern and with mget return the object values in a list. Here, is another option with bind_rows (from dplyr)

library(dplyr)
bind_cols(mget(ls(pattern = "^child\\d+$")))
# A tibble: 3 x 3
#  child1 child2 child3
#  <chr>  <chr>  <chr> 
#1 a      b      a     
#2 b      a      a     
#3 c      c      b     

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.