Maral Dorri
Maral Dorri

Reputation: 478

Apply a function with a vector output to a list of dataframes

I have a list of dataframes in my directory with a specific pattern. a sample few rows of a dataframe is shown:

> head(data[,1:3])
# A tibble: 6 x 3
  ...1   ...2  ...3
  <chr> <dbl> <dbl>
1 PLZ       1     0
2 PLZ       1     0
3 PLZ       2    11
4 PLZ       2    11
5 PLZ       3    11
6 PLZ       3    11

I want to write a function that creates a dataframe of two columns, one the name of the each of the dataframes in the list, and two the tail(data[,3], n = 1) for each of the dataframes in the list.

I try the following to first try and get last row of the third column of the dataframes:

span_function <- function(baselines) {
data <- readxl::read_excel(allfiles, sheet = "Bridge Object Girder Forces", 
                       skip = 3, col_names = FALSE)

c(max(data[,3]))
}

baselines <- list.files(pattern = "\\d+-\\d+-S00", full.names = TRUE)
Spans <-  data.frame(t(sapply(baselines, span_function)))

I get the error:

Error: `path` must be a string

Upvotes: 0

Views: 99

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

Try the following function :

span_function <- function(filename) {
  data <- readxl::read_excel(filename, 
            sheet = "Bridge Object Girder Forces", skip = 3, col_names = FALSE)
  data.frame(filename = basename(filename), value = max(data[[3]]))
}
#Assuming the regex is correct to get the files that we want.
baselines <- list.files(pattern = "\\d+-\\d+-S00", full.names = TRUE)
Spans <-  do.call(rbind, lapply(baselines, span_function))

Upvotes: 1

Related Questions