My issue consists of splitting a path, getting all the subpaths till the next "$" ocurrence (a kind of cumulative subpath) and generating a new variable for each of them.
Doing it step by step I get the desired output:
data<-data.frame(path=c("A/A/$/B/$/A/$","B/C/$","B/C/$/C/$/A/B/$"),stringsAsFactors=FALSE)
library(stringr)
data$tr<-str_count(data$path,"\\$")
data$tr_1<-substr(sapply(strsplit(data$path, "\\$"), `[[`, 1),1,nchar(sapply(strsplit(data$path, "\\$"), `[[`, 1))-1)
data$tr_2<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, 2))==TRUE,
"",
paste0(data$tr_1,substr(sapply(strsplit(data$path, "\\$"), `[`, 2),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, 2))-1)))
data$tr_3<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, 3))==TRUE,
"",
paste0(data$tr_2,substr(sapply(strsplit(data$path, "\\$"), `[`, 3),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, 3))-1)))
Trying to do the same in a loop according to Creating new named variable in dataframe using loop and naming convention, the output fails.
data<-data[,-c(4,5)]
for (i in 2:max(data$tr)) {
data[[paste0("tr_",i)]]<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, i))==TRUE,
"",
paste0(data$tr_i-1,substr(sapply(strsplit(data$path, "\\$"), `[`, i),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, i))-1)))
}
Is there another way of doing it recursively? (each new variable uses the previous one).
Thanks in advance!

