i know done in sas, can't seem figure out how done in r. so, i'm trying create multi-way proportion table of n-ways. mean -
i know how (this made example):
prop_table<-as.data.frame(prop.table(table(df$variable1,df$variable2),1)) view(prop_table) variablea variableb freq x1 y1 0.5 x2 y1 0.75 x1 y2 0.5 x2 y2 0.25
but want one-way proportions...something this:
variablea variableb freq x1 0.2 x2 0.8 x1 y1 0.5 x2 y1 0.75 x1 y2 0.5 x2 y2 0.25
is there way without separately creating 1-way, 2-way...n-way tables , appending them all?
i don't know of built in function combinations you, it's not many lines of code write own. here's such function
nprop.table <- function(x) { tbls <- map(function(n) {do.call("table", list(bquote(x[,1:.(n), drop=false]), dnn=bquote(names(x)[1:.(n)])) )}, ncol(df):1) props <- map(function(x) as.data.frame(prop.table(x,if(length(dim(x))>1){1} else {numeric(0)})), tbls) dplyr::bind_rows(props) }
we can run with
df <- expand.grid(variable1=c("x1","x2"), variable2=c("y1","y2"))[rep(1:4, c(10,60,10,20)),] nprop.table(df) # variable1 variable2 freq # 1 x1 y1 0.50 # 2 x2 y1 0.75 # 3 x1 y2 0.50 # 4 x2 y2 0.25 # 5 x1 <na> 0.20 # 6 x2 <na> 0.80
it uses columns of data.frame pass in. if had 3 columns, should still work
nsamp <- function(x, n) sample(x, n, replace=t) df <- data.frame(var1=nsamp(letters[1:3], 50), var2=nsamp(letters[4:6], 50), var3=nsamp(letters[7:8], 50)) nprop.table(df)
Comments
Post a Comment