简体   繁体   中英

Iterating through a vector of names using for loop in R

library(sjPlot)

I am using sjPlot to create quick xtabs:

sjPlot::tab_xtab(var.row = mtcars$mpg ,var.col =mtcars$wt ,show.row.prc = TRUE)

But since I am running it over many cols, I want to set up a loop:

    cols <- names(mtcars)
    for (i in cols) {
    
      sjPlot::tab_xtab(
        var.row =  mtcars$mpg,
        var.col = mtcars$i,
        show.row.prc = TRUE
      )
}

But this throws an error:

Error in table(x_full, grp_full) : 
  all arguments must have the same length

Why is this happening, and can someone please explain subsetting through iteration, or point me to a good resource?

FYI --- This does not return anything.

for (i in cols) {
  i <- 'cyl'
  
  sjPlot::tab_xtab(
    var.row =  mtcars$mpg,
    var.col = mtcars[[i]],
    show.row.prc = TRUE
  )
  
}

But this does return the chart for mpg - cyl:

for (i in cols) {

  sjPlot::tab_xtab(
    var.row =  mtcars$mpg,
    var.col = mtcars$cyl,
    show.row.prc = TRUE
  )
  
}

Thanks for the comments, this is the solution, but still looking for some understanding. Why mtcars[[i]] instead of mtars[i]? Why doesn't mrcars$i work?

for (i in cols) {

  plt <- sjPlot::tab_xtab(
    var.row =  mtcars$mpg,
    var.col = mtcars[[i]],
    show.row.prc = TRUE
  )
  print(plt)
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM