I've have a hard time to get a function within a function for multiple Dataframes.
I have multiple Dataframes: all looks like
A <- data.frame(Date = as.character(c("Jan-22", "Dec-21", "Nov-21", "Oct-21")),
City1 = seq(1:4),
City2 = seq(1:8))
But some dataframes have some more Cities (3 to 8). I want to run the following code for all Dataframes:
Dates_A <- A$Date
A$Date <- NULL
nm1 <- combn(names(A), 2, FUN = paste, collapse = "_")
A[nm1] <- combn(A, 2, FUN = function(x) abs(x[[1]]- x[[2]]))
Casava$A<- Dates_A
which works with my first Dataframe. So I tried to put all my Dataframes to a list
dfList <- list(A, B, C, D, E)
And put the code in a loop:
for (i in 1: length(dfList))
{
Dates_i <- dfList[i]$Date
dfList[i]$Date <- NULL
nm1 <- combn(names(dfList[[i]]), 2, FUN = paste, collapse = "_")
dfList[i][nm1] <- combn(dfList[[i]], 2, FUN = function(x) abs(x[[1]]- x[[2]]))
dfList[i] <- select(dfList[[i]], contains("_"))
dfList[i]$Dates <- Dates_i}
but now I get the Error:
Error in x[[1]] - x[[2]] : non-numeric argument to binary operator
May can someone help? im not to familiar with loops.
Edit: sorry I corrected the first code whicht I run on a single Dataframe (3 I only had because I tried it - that will not work I now, 2 is what I want).
My Code than breaks only within the loop at the point
dfList[i][nm1] <- combn(dfList[[i]], 2, FUN = function(x) abs(x[[1]]- x[[2]]))
I would do it slightly differently. I would wrap everything in a function and apply, i.e.
Then apply the function to your list, i.e.
DATA