class<- c('A','B')
var2<- c(1,0)
var3 <- c(0,1)
df<- data.frame(class,var2,var3)
for (i in colnames(df)[2:3])
{
#print(i)
table(paste0('df$',i), df$class)
}
results in error ‘all arguments must have the same length’. Also tried putting get(paste0('df$',i))
Is there a way to loop through these columns and tabulate?
>Solution :
The issue with your code is that because paste0() returns a character vector e.g, ‘var2’ and is not a correct argument for table() function. You can use the double bracket ‘[[‘ to extract the columns:
# create a list to save the results from loop
tl<-vector(mode = 'list')
# run the loop and add the results for each column in the corresponding element of 'tl'
for (i in colnames(df)[2:3]) {
tl[[i]]<-table(df[[i]], df$class)
}
output
tl
$var2
A B
0 0 1
1 1 0
$var3
A B
0 1 0
1 0 1
alternatively you can use lapply() function:
lapply(df[, 2:3], function(x) table(x, df$class))
var2
x A B
0 0 1
1 1 0
$var3
x A B
0 1 0
1 0 1