'Indexing dataframe within a loop

I'ld like to extract specific data from a log-data.

In R it looks like that Data Frame

I need values from Data$Time of the cases, where Data$Data_Type == "DATA". So I tried this:

chars_2 <- "DATA"
Liste <- c()
x <- 0

for (i in Data$Data_Type){
if(grepl(chars_2, i)== TRUE)
 x <- Data[Data$Data_Type == "i", Data$Time]
{List<-c(List, x)}
}

, but the part with Data$Data_Type == "i" doesn't seem to work. How can I make this work?

And moreover: Is there a way, I can only take the first value (first row) from when my index of the loop "i" changes from "EXP" to "DATA" and the last value/row, before it changes from "DATA" to EXP". I need the whole timespans for every sequences, where Data$Data_Type == "DATA".

Thanks for help!



Solution 1:[1]

library(tidyverse)

Data <- tribble(~"Time", ~"Data_Type", ~"Content", 
                40.95,"EXP","Box_5: autoDraw = TRUE",
                40.95,"EXP","Box_6: autoDraw = TRUE",
                42.39,"DATA","Keypress: q",
                42.80,"DATA","Keypress: tab")

chars_2 <- "DATA"

Data %>% 
  dplyr::filter(Data_Type == chars_2) %>% 
  dplyr::pull(Time) %>% 
  as.list()

I see that you want the output as a list. This should do it.

Solution 2:[2]

I've found the solution:

chars_2 <- "DATA"
chars_3 <- "Box_9: autoDraw = True"
LogData_M <- as.matrix(LogData)
Latency_Case <- 0
Latency <- c()
i <- 0
while (i < length(LogData_M[,2])){
  i <- i + 1
  if(grepl(chars_3, LogData_M[i,3]) == TRUE){
    j <- i + 1
    while(grepl(chars_2, LogData_M[j,2])== TRUE){
    j <- j +1
    }
    j <- j - 1
    a <- as.numeric(LogData_M[j,1])
    b <- as.numeric(LogData_M[i,1])
    Latency_Case <- a- b
    Latency <- c(Latency, Latency_Case)
    i <- j + 1
}
}

This question can get closed :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anurag N. Sharma
Solution 2 David