1

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.

2 Answers 2

1
  • You are passing y as an argument to the function but using x inside.
  • For the last line I think you mean mean(x_$DIF)
library(tidyverse)

meanChange <- function(x) {
  colnames(x) <- str_replace_all(colnames(x), "\\.\\d", "")
  x_ <- filter(x, WEEK >= 26)
  mean(x_$DIF) 
}
  • Put the dataframes in a list and use sapply to apply the function.
y <- list(df, df2, df3)
sapply(y, meanChange)
Sign up to request clarification or add additional context in comments.

Comments

1

This is a possibile solution:

# create a list of your dataframes
dfl <- list(df, df2, df3)

# apply mean function 
lapply(1:3, function(i) mean(dfl[[i]][[2]][which(dfl[[i]][[1]] >= 26)]))

Index i selects the single dataframe into list dfl. [[1]] and [[2]] select respectively column 1 and column 2 of each dataframe.


Another possible solution is:

lapply(dfl, function(x) mean(x[[2]][which(x[[1]] >= 26)]))

Here lapply works directly with dfl without index.


NOTE: both solutions return a list as a result. If you want a vector use sapply rather than lapply

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.