Reputation: 847
I've been trying to find a way to calculate the proportion of 1 count in each row in R.
For example, in following data. 15090 is have one 1 in 5 votes, so his proportion is 0.2
In the next row, he has four 1s out of 5 votes, so the proportion is 0.8.
I need to make NA to be dismissed in the calculation, i.e. should not be included in the denominator.
ICPSR Vote.335 Vote.354 Vote.971 Vote.972 Vote.973 Vote.155 Vote.295
15090 0 0 0 1 0 NA NA
29300 1 1 1 0 1 NA NA
What code should in R, to calculate each row's proportion of 1?
Thank you in advance!
Upvotes: 0
Views: 2279
Reputation: 81743
If the columns contain 0
s and 1
s only, you can use
rowMeans(dat[-1], na.rm = TRUE)
#[1] 0.2 0.8
where dat
is the name of your data frame.
Upvotes: 1
Reputation: 121608
Here a vectorized solution using rowSums
:
dat <- dat[,-1]
rowSums(dat==1,na.rm=TRUE)/rowSums(!is.na(dat))
[1] 0.2 0.8
where dat
:
dput(dat)
structure(list(ICPSR = c(15090L, 29300L), Vote.335 = 0:1, Vote.354 = 0:1,
Vote.971 = 0:1, Vote.972 = c(1L, 0L), Vote.973 = 0:1, Vote.155 = c(NA,
NA), Vote.295 = c(NA, NA)), .Names = c("ICPSR", "Vote.335",
"Vote.354", "Vote.971", "Vote.972", "Vote.973", "Vote.155", "Vote.295"
), class = "data.frame", row.names = c(NA, -2L))
Upvotes: 1