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

using table() with for loop

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?

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

>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
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