Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't my FOR loop in R working? While any single step works

list<-c("a2012","a2013")

a2012<-c("al,","al,rb,","cu,pvc,")
a2013<-c("ab,al,","al,cu,","pvc,al,")

sum(str_count(a2012,"al,")==1)
[1] 2
sum(str_count(a2013,"al,")==1)
[1] 3

output <- vector("integer")
for(i in seq_along(list))
{
output[[i]]<-sum(str_count(list[[i]],"al,")==1)
}
output
[1] 0 0

This is the whole process. I’m pretty much a noob.

I don’t know why this happens. Please help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

a2012<-c("al,","al,rb,","cu,pvc,")
a2013<-c("ab,al,","al,cu,","pvc,al,")

mylist <- list("a2012" = a2012,
               "a2013" = a2013)

output <- vector("integer")
for(i in seq_along(mylist))
    {
      output[[i]]<-sum(str_count(mylist[[i]],"al,")==1)
    }

> output
[1] 2 3

> mylist
$a2012
[1] "al,"     "al,rb,"  "cu,pvc,"

$a2013
[1] "ab,al,"  "al,cu,"  "pvc,al,"

The main thing is that your list doesn’t need to contain names and then refer to variables by those names – it can just contain the vectors themselves.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading