r - Calculate proportion by groups for a subset of the dataset -
this might simple, since im not getting it, im posting here hope help.
i want calculate proportion , standard error of proportion grouping dataset of categorical variables. have 2 variables v1
1 4 , v2
1 9. want calculate proportion of 1 (also 2,3...9 ( in v2
)) grouping of v1
.
to hand easy because utilize of table(v1, v2)
, dont want hand :)
said in more simple way: want find % can utilize mean numeric variable. have 1000 people, 300 in category 1 of v1
, 200 in category 2 of v1
etc. same v2
, 400 in category 1 , on. if calculate % of category 1 (v1
) groups of v2
, 300/400, 200/400 , on.
dataframe sample
id v1 v2 1 1 1 2 1 1 3 2 1 4 2 1 5 3 2 6 3 2 7 4 2
desired output: propotion grouping v2: grouping 1 (v2=1) 2/4; 2/4; 2/4; 1/4. v2: grouping 2 (v2=2) 2/3; 2/3; 2/3; 1/3
hope makes sense!
try:
library(data.table) setdt(dt)[v1==1,list(meanv2=mean(v2), sev2=se(v2)),by=v3]
if v1==1 , mean(v1) equal 1.
r
No comments:
Post a Comment