1

I'm new to R and really appreciate if I can get some help here.

I have a list of datasets based on dates. So df_1_1, df_1_2... df_1_31. I plan to use a scoring function for each datasets. For example, score1.1<-score(df_1_1), and I will get scoreA, score B for the day 1-1, and so on. I will then combine all the scores using rbind(score1.1, ..., score1.31).

I can do this by typing all the datasets, but is there a more efficient way to do this? like in a for loop

Thanks!

TL16
  • 61
  • 7
  • Please revise your question to include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – cmaher Feb 14 '18 at 17:56
  • I'd suggest you read my answer at [How to make a list of data frames?](https://stackoverflow.com/a/24376207/903061), probably closeable as a dupe of that... something like: `df_list = mget(ls(pattern = "df_")); score_list = lapply(df_list, score); result = do.call(rbind, score_list)` – Gregor Thomas Feb 14 '18 at 17:57
  • Thanks! This is really helpful! – TL16 Feb 15 '18 at 01:27

1 Answers1

1

take a look at this example that I think accomplishes what you are trying to do. Note that I have put the scores into a dataframe as you requested, even though they could more appropriately fit into a list or vector.

Create simple dataframes:

n1 = c(1, 2 ,3)
n2 = c(4, 5, 6)
m1 = c(7, 8, 9)
m2 = c(10, 11, 12)
df1 <- data.frame(n1, m1)
df2 <- data.frame(n2, m2)

Declare scoring function for dataframes:

score <- function(df) {
  return((mean(df[,1] + mean(df[,2])))/2)
}

Iterate over dataframes while scoring each and assigning to new variable:

dfs <- list(df1, df2)
for (i in 1:length(dfs)) {
   x <- score(dfs[[i]])
   assign(paste0("score",i), as.data.frame(x))
}

Rbind resulting single-celled dataframes together

scores <- rbind(score1, score2)

Let me know if this helps, or if I can adjust the solution to better fit your use case. :)

ADF
  • 173
  • 10