Reputation: 13969
I would like to calculate the marginal probability distributions from a dataframe containing raw binary data. I'm sure there is an easy way, however I can not seem to find a function for it. Any ideas? I'm attaching a simple example of a dataframe of binary variables where an outcome can be considered as one and no outcome as 0.
set.seed(1234)
respondent <- 1:1000
red <- sample(0:1, 1000, replace=T)
blue <- sample(0:1, 1000, replace=T)
green <- sample(0:1, 1000, replace=T)
black <- sample(0:1, 1000, replace=T)
grey <- sample(0:1, 1000, replace=T)
my.new.df <- data.frame(respondent, red ,blue,green,black,grey)
lapply(my.new.df[,2:6],sum)
$red
[1] 518
$blue
[1] 485
$green
[1] 515
$black
[1] 481
$grey
[1] 508
Upvotes: 0
Views: 2334
Reputation: 940
You can use:
colMeans(my.new.df[,2:6])
Or as @moto said and you were trying (but more simple):
lapply(my.new.df[,2:6], function(x) mean(x))
Upvotes: 1