Nested forloop - adding rows to dataframe

Hello,

I'm quite new to the R programming language and it seems I might need some help with a forloop.

I aim at extracting some data out of an existing data frame so that in the end I should have a matrix with a row for each subject. At the moment, each subject is represented with several values per variable and I need to calculate the mean value per variable and subject.

This is my code so far:

dat <- data.frame(cbind(rep(c(1:3), each = 3), 
                        matrix(runif(36, min=2, max=6), 
                               nrow=9, ncol = 4)))
names(dat)[1:5]<-c("subject","PD50","PD100","PD150","PD200")


library(dplyr)
#> 
#> Attache Paket: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
foo.mean=c()                  ## create empty containers
foo.total=c()                 ## create empty containers
all.sub = unique(dat$subject) ## create vector with all subject numbers

for(j in 1:length(all.sub)){  ## for loop over subjects
  for(i in 1:4){              ## for loop over variables
    a <- subset(dat, dat$subject==all.sub[[j]] , select=paste("PD", i*50, sep=""))
    foo.mean<-cbind(foo.mean,colMeans(a)) ## 
  }
  foo.total[j,]<-foo.mean[1,c((-3+4*j):4*j)]  ## FINAL DATAFRAME 
                                              ## one row per subject with 4 variables each
}
#> Error in foo.total[j, ] <- foo.mean[1, c((-3 + 4 * j):4 * j)]: falsche Anzahl von Indizes für Matrix

Obviously, the place holder foo.mean is getting longer and longer with each subject (it would be better to restart the object foo.mean from zero with each subject). That's why I created the - not so elegant - solution of extracting the 1:4, 5:8, etc. columns and adding each 4 columns to a new row in a dataframe. Unfortunately, this isn't working.

So, I have two questions:

  1. How can I create j (=number of subjects) different objects foo.mean within my loop? Each should contain the 4 average values of the previous data.
  2. How can I add those foo.mean-objects to the rows of a new dataframe (one row per subject)?

I already tried working with lists, the command rbind, but haven't found a solution yet. I appreciate any help! Thank you very much in advance,
Susanne

See the FAQ: How to do a minimal reproducible example reprex for beginners, please, because questions are hard helpfully to address in the abstract. Right now, all I can suggest is that R is best addressed as a functional language, rather than an imperative one. Taken as pcode, the example is perfectly fine and would translate easily into Python, for example, but not so well into R, which requires tricks to deal with both i and j indices at the same time.

Thank you very much, I will edit my question!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.