How to make 'for(){}' code simpler in R? -


thanks comment of matthew lundberg, here attach simplified example of want do.

>id = c("a", "b") >citations = c("p,q", "p,q,r,x") >database = data.frame(id, citations) >database   id        citations 1         p,q 2 b         p,q,r,x 

here want convert 'database' 'datanetwork' below:

>datanetwork          p       q b       p b       q b       r b       x 

according robert krzyzanowski answered question, reduce seems useful. there other useful ways have?


i new r, , made code convert csv file network file (from, to) network analysis in pajek, using 'for(){}' below. know there great way make code simpler in r using apply function family, i'm not used it. thus, please me make code simpler? in advance.

myfile = file.choose() mydata = read.csv(myfile) dataa = data.frame(mydata$cola, mydata$colb)   id = as.vector(dataa[,1]) citationbase = strsplit(gsub(" \\|", "/", dataa[,2]), "/")  = c(0) = c(0) datab = data.frame(from, to)  m=1 #m: how many backward citations in data? for(i in 1:length(dataa[,1])){ #i: how many issue numbers in data?   citations = as.vector(citbase[[i]])   k=1   for(m in m:(m+length(citations)-1)){     datab[m,1] = id[i]     datab[m,2] = citations[k]     k = k+1   }   m = m+1  } 

an lapply isn't necessary here, since using previous computation's result. use reduce keep functional. way, notice m is i in each iteration of outer loop!

datab <- reduce(function(df, i) {   citations <- as.vector(citbase[[i]])   inner_seq <- seq(m, m + length(citations)-1)   df[inner_seq, ] <- list(rep(id[i], length(inner_seq)), citations[inner_seq - m + 1])   df }, seq_len(nrow(dataa)), datab) 

Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -