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

Use i in variable r

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")
}

>Solution :

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

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

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