combine data frames from different dates in a loop

TL16 Source

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




answered 6 months ago Ari Decter-Frain #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]])

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. :)

comments powered by Disqus