Reputation: 1080
I'm trying to replace my for loop in R with lapply.
Table <- c("Filepath1","Filepath2")
Conditions c<- c("Yes","No")
for (i in 1:length(Table)){
Df[[i]] <- readxl::read_xlsx(Table[i])
Df[[i]]$Condition <- Conditions[i]
}
So this takes the first element in Table, reads it into R and then adds a column to the table corresponding to the first element in Conditions.
using lapply I can add the tables in by:
lapply(Table, readxl::read_xlsx)
I could say:
Df[[1]]$Conditions <- Conditions[1]
Df[[2]]$Conditions <- Conditions[2]
But how do I add this extra column in without the use of for-loops?
Upvotes: 1
Views: 74
Reputation: 70653
You can iterate through both objects (table and condition) using mapply
. Untested:
mapply(FUN = function(tbl, cnd) {
out <- readxl::read_excel(tbl)
out$Condition <- cnd
out
}, tbl = Table, cnd = Conditions)
Upvotes: 2