On_an_island
On_an_island

Reputation: 509

R - working with list within a list of data frames

I have a list of two data frames df1 and df2. Each data frame contains three columns val1 val2 and bb. Nested within bb is another list of 2 with four columns - see tail(my.list$df1, n=3) below.

When I export using write.csv, all columns are present in the .csv file and the output looks exactly like tail(my.list$df1, n=3). However, I would like to - for a lack of better terms - shift the bb.dn bb.mavg bb.up bb.pctB columns up one level up so that I am able to call, manipulate, and/or merge columns bb.dn bb.mavg bb.up bb.pctB with other data frames or lists in my code.

Reproducible:

library(TTR)
library(tidyverse)
library(plyr)

# reproducible example
set.seed(1363)
d1 <- data.frame(val1 = c(rnorm(n=65, mean=15)), val2 = c(rnorm(n=65, 
mean=15)))
d2 <- data.frame(val1 = c(rnorm(n=35, mean=12)), val2 = c(rnorm(n=35, 
mean=25)))
my.list <- list(df1 = d1, df2 = d2)

for (i in seq_along(my.list)) {
  my.list[[i]] <- my.list[[i]] %>%
    mutate(bb = BBands(val2, n = 20, sd = 2))
}

This is the structure of data frame 2 within my.list:

> str(my.list$df2)
'data.frame':   35 obs. of  3 variables:
$ val1: num  11.1 11.4 10.9 13.9 12.6 ...
$ val2: num  25.1 25.7 24.6 25.2 26 ...
$ bb  : num [1:35, 1:4] NA NA NA NA NA NA NA NA NA NA ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr  "dn" "mavg" "up" "pctB"

This is the list within the 'list of 2' that contains the 4 columns I'd like to shift up one level:

> tail(my.list$df1, n=3)
     val1     val2      bb.dn    bb.mavg      bb.up    bb.pctB
63 16.29825 15.64776 13.4178099 15.3927881 17.3677663  0.5645507
64 15.89625 14.77928 13.4214305 15.3943781 17.3673258  0.3441171
65 12.59590 15.43764 13.4202751 15.3533071 17.2863391  0.5218149
> 

Upvotes: 2

Views: 113

Answers (2)

akrun
akrun

Reputation: 887951

We can use map from purrr

library(purrr)
map(my.list, as.data.frame.list) 

data

set.seed(1363)
d1 <- data.frame(val1 = c(rnorm(n=65, mean=15)), 
            val2 = c(rnorm(n=65, mean=15)))

d2 <- data.frame(val1 = c(rnorm(n=35, mean=12)), 
             val2 = c(rnorm(n=35, mean=25)))
my.list <- list(df1 = d1, df2 = d2) 
for(i in seq_along(my.list)) my.list[[i]][["bb"]] <- 
                              BBands(my.list[[i]]$val2, n=20, sd = 2)

Upvotes: 2

Onyambu
Onyambu

Reputation: 79348

You are looking for:

 setNames(Map(do.call,c(data.frame),my.list),names(my.list))

Upvotes: 1

Related Questions