[R] How to extract same columns from identical dataframes in a list?

Dénes Tóth toth.denes at ttk.mta.hu
Mon Feb 8 18:00:07 CET 2016


Hi,

Although you did not provide any reproducible example, it seems you 
store the same type of values in your data.frames. If this is true, it 
is much more efficient to store your data in an array:

mylist <- list(a = data.frame(week1 = rnorm(24), week2 = rnorm(24)),
                b = data.frame(week1 = rnorm(24), week2 = rnorm(24)))

myarray <- unlist(mylist, use.names = FALSE)
dim(myarray) <- c(nrow(mylist$a), ncol(mylist$a), length(mylist))
dimnames(myarray) <- list(hour = rownames(mylist$a),
                           week = colnames(mylist$a),
                           other = names(mylist))
# now you can do:
mean(myarray[, "week1", "a"])

# or:
colMeans(myarray)


Cheers,
   Denes


On 02/08/2016 02:33 PM, Wolfgang Waser wrote:
> Hello,
>
> I have a list of 7 data frames, each data frame having 24 rows (hour of
> the day) and 5 columns (weeks) with a total of 5 x 24 values
>
> I would like to combine all 7 columns of week 1 (and 2 ...) in a
> separate data frame for hourly calculations, e.g.
>> apply(new.data.frame,1,mean)
>
> In some way sapply (lapply) works, but I cannot directly select columns
> of the original data frames in the list. As a workaround I have to
> select a range of values:
>
>> sapply(list_of_dataframes,"[",1:24)
>
> Values 1:24 give the first column, 25:48 the second and so on.
>
> Is there an easier / more direct way to select for specific columns
> instead of selecting a range of values, avoiding loops?
>
>
> Cheers,
>
> Wolfgang
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list