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

Time:02-02

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

CodePudding user response:

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.

  •  Tags:  
  • r
  • Related