Sylvain
Sylvain

Reputation: 143

Using lapply and an anonymous function in a list of data frames

In a list of data frames listdf , I want to determine the mean, max, min, stdv and the number or rows (number of values) for the column Concentration in each data frame :

mean <- lapply(listdf, function(x) {mean(x$Concentration, na.rm = F)})
max <- lapply(listdf, function(x) {max(x$Concentration, na.rm = F)})
min <- lapply(listdf, function(x) {min(x$Concentration, na.rm = F)})
sd <- lapply(listdf, function(x) {sd(x$Concentration, na.rm = F)})
nbr <- lapply(listdf, function(x) {nrow(x$Concentration, na.rm = F)})

However, nrow does not work with lapply and a function. How can I modify it ?

Also, is it possible to add (via lapply and a function or tibble ?) an additional sixth list of analysis for listdf to tell that the number of rejected data frames in listdf is "NA" ? I know it because I selected in listdf all the data frames without rejected values, but I wish to add this step in the script for further analysis.

nbr_rejected <- lapply(listdf, ??? "NA") 

(nbr_rejected="NA")

Upvotes: 0

Views: 184

Answers (1)

slava-kohut
slava-kohut

Reputation: 4233

You can use length:

a <- list(mtcars, mtcars)
lapply(a, function(x) {length(x$hp[!is.na(x$hp)])})

EDIT Your second question:

a <- list(mtcars, mtcars)
lapply(a, function(x) {data.frame(value = matrix(NA, nrow(x), 1))})

Upvotes: 1

Related Questions