简体   繁体   English

在 R 中使用 for 循环遍历名称向量

[英]Iterating through a vector of names using for loop in R

library(sjPlot)

I am using sjPlot to create quick xtabs:我正在使用 sjPlot 创建快速 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:但这确实返回了 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]?为什么是 mtcars[[i]] 而不是 mtars[i]? Why doesn't mrcars$i work?为什么 mrcars$i 不起作用?

for (i in cols) {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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