Problem
I want to use a function to get the mean numbers from different dataframes.
Example dataframes
WEEK.1 <- 1:52
DIF.4 <- runif(52, 0, 20)
df <- as.data.frame(cbind(WEEK.1, DIF.4))
WEEK.2 <- 1:52
DIF.5 <- runif(52, 0, 20)
df2 <- as.data.frame(cbind(WEEK.2, DIF.5))
WEEK.3 <- 1:52
DIF.6 <- runif(52, 0, 20)
df3 <- as.data.frame(cbind(WEEK.3, DIF.6))
Attempt
a) Without a function, I'd have to repeat the following three times:
colnames(df) <- str_replace_all(colnames(df), "\\.\\d", "")
df_ <- filter(df, WEEK >= 26)
mean(df_$DIF)
b) My attempt to do so with a function:
meanChange <- function(x) {
colnames(x) <- str_replace_all(colnames(x), "\\.\\d", "")
x_ <- filter(x, WEEK >= 26)
mean(x_$DIF)
}
x <- c("df", "df2", "df3")
changes <- as.data.frame(lapply(x, meanChange))
Result
Error in `colnames<-`(`*tmp*`, value = character(0)) :
attempt to set 'colnames' on an object with less than two dimensions
Called from: `colnames<-`(`*tmp*`, value = character(0))
Browse[1]> Q
Help would be appreciated.