mercredi 21 août 2019

How to use nested for loops for data frame with multiple levels in r

I would like to use for loops for my data frame with multiple levels: data[[level 1]][["level 2"]][[level 3]] level 1: four different files level 2: with each a number of columns level 3: with each a number of values

I was able to write a functional for loop when I set the first level to a fixed value. However, I would like to be able to use the loop on all four files.

Following is the code I'm using for the for loop.

```from <- 2
```to <- length(data[[1]][["Streckenmeter.auf.dem.Modul.m."]])
```diff <- 0 

```StartEinmal <- TRUE
```StartPunkt <- 0 
```nm<-0

```for (i in from:to) { 
```  diff <- data[[1]][["Streckenmeter.auf.dem.Modul.m."]][[i]]- 
``` data[[1]][["Streckenmeter.auf.dem.Modul.m."]][[i-1]]
```  if (diff > 1) 
```    nm <- nm + 1
```  if ((data[[1]][["speed.m.s."]][[i]])> 5 & StartEinmal == TRUE) {
```    StartPunkt=i
```    StartEinmal=FALSE
```  }
```  if (nm == 13 & as.integer(data[[1]][["Streckenmeter.auf.dem.Modul.m."]][[i]]) > 10 & EndEinmal == TRUE) {
```    EndPunkt = i 
```    EndEinmal = FALSE
```    print(data[[1]][["Streckenmeter.auf.dem.Modul.m."]][[i-1]])
```  }
```}

To do these calculations for every file, I tried:

```for (i in length(data)) { 
```for (j in from:to) {
```  diff <- data[[i]][["Streckenmeter.auf.dem.Modul.m."]][[j]] - ```data[[i]][["Streckenmeter.auf.dem.Modul.m."]][[j-1]]
```  if (diff > 1) 
```    nm <- nm + 1
```  if ((data[[i]][["speed.m.s."]][[j]])> 5 & StartEinmal == TRUE) {
```    StartPunkt=j
```    StartEinmal=FALSE
```  }
```  if (nm == 13 & as.integer(data[[i]][["Streckenmeter.auf.dem.Modul.m."]][[j]]) > 10 & EndEinmal == TRUE) {
```    EndPunkt = j 
```    EndEinmal = FALSE
```    print(data[[i]][["Streckenmeter.auf.dem.Modul.m."]][[j-1]])
```  }
```}}


However, I get the error message: Error in data[[i]][["Streckenmeter.auf.dem.Modul.m."]][[j]] : 
  subscript out of bounds

I would like to get an output data.frame with i x j values for my "StartPunkt" and "Endpunkt" 

Thank you a lot for looking into it. I would appreciate any help on where to find information or how to do this (is it possible to have to unknown variables in a loop?)

Aucun commentaire:

Enregistrer un commentaire