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.