-1

I am very new to R and would appreciate any advice. I am from a STATA background and so learning to think in R. I am trying to produce tables of percentages for my 20 binary variables. I have tried a for loop but not sure where I am going wrong as there is no warning message.

for (i in 1:ncol(MAAS1r[varbinary])) {
  varprop<- varbinary[i]
  my.table<-table(MAAS1r[varprop])
  my.prop<-prop.table(my.table)
  cbind(my.table, my.prop)
}

Many thanks

sara_khan
  • 21
  • 6
  • Hi Sara: Can you show as some of your data? how does varbinary looks like, you can show as by using `dput(varbinary)` and pasting the result in your question, that will help us answer – Derek Corcoran Jan 13 '17 at 16:21
  • no problem, happy to help, I think I have the solution to your problems – Derek Corcoran Jan 13 '17 at 16:27
  • I have stored all 24 of my binary variables in varbinary. Really sorry - I am trying to paste the code but whenever I hit Enter, my reply gets posted. It is c("binary1", "binary2", "binary3",........,"binary24"). I hope that helps. – sara_khan Jan 13 '17 at 16:27
  • http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610 – alistaire Jan 13 '17 at 16:53
  • `lapply(mtcars, function(x){prop.table(table(x))})` – alistaire Jan 13 '17 at 16:55

1 Answers1

0

I made one with an example extracted from mtcars

this are two variables that are binary (0 or 1), called VS and AM

mtcarsBivar<- mtcars[,c(8,9)]

get names of the columns:

varbinary <- colnames(mtcarsBivar)

use dplyr to do it:

library(dplyr)

make an empty list to populate

Binary_table <- list()

now fill it with the loop:

for (i in 1:length(varbinary)) {
  Binary_table[[i]] <- summarise(mtcarsBivar, percent_1 = sum(mtcarsBivar[,1] == 1)/nrow(mtcarsBivar))  
}

Transform it to a data frame

Binary_table <- do.call("cbind", Binary_table)

give it the name of the varbinary to the columns colnames(Binary_table) <- varbinary

this only works if all your variables are binary

Derek Corcoran
  • 3,930
  • 2
  • 25
  • 54