2

I have a list of lists of dataframes:

library(dplyr)
library(magrittr)

a <- list(first = data.frame(x=runif(1), y=runif(1)),
          second = data.frame(x=runif(5), y=runif(5)))
b <- list(first = data.frame(x=runif(1), y=runif(1)),
          second = data.frame(x=runif(5), y=runif(5)))
a <- a %>% set_names(1:length(a))
b <- b %>% set_names(1:length(b))
c <- list(a, b)
c <- c %>% set_names(1:length(c))

I want to assign the two levels of list names as new columns to the dataframe, and then bind them into one dataframe. The desired output is something like:

  x    y   name1   name2
.23  .43       1       1
.23  .43       1       2
.23  .43       2       1
.23  .43       2       2

Where the values of x and y are not the point. I am struggling with this as lapply does not access the name of the element of the list.

Thanks.

2
  • The code produced errors on my end after the lines containing %>% . (I have dplyr loaded). I presume you use a package like magrittr? may be good to know for those who want to replicate the question. Commented Jan 19, 2015 at 7:14
  • Don't use c as a name for your list. Commented Jan 19, 2015 at 8:27

1 Answer 1

2

May be this helps:

library(reshape2)
library(tidyr)
library(dplyr)
res <- melt(c) %>%
             group_by(variable) %>% 
             mutate(indx=row_number()) %>%
             spread(variable, value) %>% 
             ungroup() %>% 
             select(-indx)
Sign up to request clarification or add additional context in comments.

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.