Home > Net >  Use i in variable r
Use i in variable r

Time:04-07

I want to use the i variable to loop over this piece of code, each iteration changing FAQ$q1 to FAQ$q2, FAQ$q3. How can I do this?

for(i in 1: 19){
  yes <- table(FAQ$q1)[1]
  no <- table(FAQ$q1)[2]

  b <- barplot(table(FAQ$q1),
          main="Did you have any difficulties using the chatbot?",
          ylab="Count",
          names.arg = c("yes", "no"),
          col="blue",
          ylim = c(0,28))
  abline(v=c(1.3) , col="grey")
  text(b, y=c(yes 1,no 1), paste("n: ", c(yes,no) , sep=""), cex=1, col = "red")
}

CodePudding user response:

We can use paste to create a string for the column name and extract with [[ (as $ will try to match literally). If we want to redirect the plots to a single pdf, then write the plots to pdf. In the code, table function was applied on the same column multiple times, instead, do it once and create an object ('tbl1') which is reused as necessary

pdf("path/to/file.pdf")
for(i in 1:19){
  colnm <- paste0("q", i)
  tbl1 <- table(FAQ[[colnm]])
  yes <- tbl1[1]
  no <- tbl1[2]

  b <- barplot(tbl1,
          main="Did you have any difficulties using the chatbot?",
          ylab="Count",
          names.arg = c("yes", "no"),
          col="blue",
          ylim = c(0,28))
  abline(v=c(1.3) , col="grey")
  text(b, y=c(yes 1,no 1), paste("n: ", c(yes,no) , sep=""), cex=1, col = "red")
}
dev.off()

The difference in paste0 and paste is in the sep. By default paste uses sep = " " where as it is "" in paste0

  • Related