I have data in a text file in which the cases are stacked in a single column. I need to extract selected lines from each case into vectors. I know how to do this with a loop that parses every line, but I'd like to know if this can be done in R without using a loop.
Here's a demo data frame:
demodat <- data.frame(V1 = c(
"case01",
"sid: 112905",
"form3: 2",
"form2: 0",
"form1: An interesting comment",
"form0: 8",
"case02",
"sid: 132788",
"form3: 1",
"form2: 1",
"form1: Not sure about this",
"form0: 17",
"case03",
"sid: 102296",
"form3: 1",
"form2: 0",
"form1: This is obvious",
"form0: 12"))
Here's an example of the loop I'm using to extract case, form0, and form1 into vectors:
library(tidyverse)
datlines <- 6 # Number of rows per case
case <- NA
form0 <- NA
form1 <- NA
j <- 1
for(i in 1:nrow(demodat)) {
if (str_sub(demodat[i,1],1,4)=="case") case[j] <- demodat[i,1]
#
if (str_sub(demodat[i,1],1,6)=="form0:") form0[j] <- str_replace(demodat[i,1],"form0: ","")
if (str_sub(demodat[i,1],1,6)=="form1:") form1[j] <- str_replace(demodat[i,1],"form1: ","")
#
if(i%