Home > OS >  Iterating through two vectors in a for loop R
Iterating through two vectors in a for loop R

Time:11-01

I want to create a for loop where it calculates the standard deviation of vectA and then vectB. It would display the the name of the vector it would calculate the std() of and then print the std value for it. How would I be able make the code down below work?

vectA <- c(1,6,7)
vectB <- c(8,9,11)
names <- c('A', 'B')
vects <- c(vectA,vectB)
for (i in seq_along(scale_vars)) {
     print("Calculating for", names[i])
     std(vects[i])
}

CodePudding user response:

If you concatenate vectors using c(), they form one long vector. In your case, vects has length 6 and is just c(1,6,7,8,9,10). You have to use lists to create collections of vectors where you can call them by index. Also, the function for standard deviation is sd() and you can't print two characters with the same print statement. You need to paste() them first. And names is reserved.

Try this:

vectA <- c(1,6,7)
vectB <- c(8,9,11)
vnames <- c('A', 'B')
vects <- list(vectA,vectB)
for (i in 1:2) {
  print(paste("Calculating for", vnames[i]))
  print(sd(vects[[i]]))
}

You could also make it easier by naming the vectors in the list:

vectA <- c(1,6,7)
vectB <- c(8,9,11)
vects <- list("A"=vectA,"B"=vectB)
for (i in names(vects)) {
  print(paste("Calculating for", i))
  print(sd(vects[[i]]))
}
  • Related