putting variables into vectors to be used in subsequent function (R) -
i have question regarding second function not producing wanted to
#example mt-cars selected_cyl_6 <- subset(mtcars, mtcars$cyl==6) selected_cyl_4 <- subset(mtcars, mtcars$cyl==4) count <- function(variable,group) { sum(group[[deparse(substitute(variable))]]== 4) } #now create matrix results here below: #example u<-count(gear,selected_cyl_6) v<-count(carb,selected_cyl_6) w<-count(gear,selected_cyl_4) x<-count(carb,selected_cyl_4) matrix(c(u,v,w,x), byrow=true, ncol=2, nrow=2)
this feasible option, love convert lines above function because in dataset there lot more variables , save lot of time , code length. tried following code:
variables_of_interest <- c("gear","carb") groups_of_interest <- c("selected_cyl_6","selected_cyl_4") alteration_multiple <- function(variable_vector, group_vector){ m.results <- matrix(0, nrow = length(variable_vector), ncol = length(group_vector)) rownames(m.results) <- variable_vector colnames(m.results) <- group_vector (t in 1:length(group_vector)) { (i in 1:length(variable_vector)) { m.results[i,t] <- count(group_vector[t],variable_vector[i]) } print(m.results) } } alteration_multiple(variable_vector=variables_of_interest, group_vector=groups_of_interest)
any suggestions? thank support!
if redefine inputs , count
can considerably simplified , shortened. (selected_cyl_4
, selected_cyl_6
in question.)
groups <- list(cyl_6 = selected_cyl_6, cyl_4 = selected_cyl_4) ## variables <- c(gear = "gear", carb = "carb") ## count <- function(v, g) sum(g[[v]] == 4) outer(variables, groups, vectorize(count))
giving:
cyl_6 cyl_4 gear 4 8 carb 4 0
note: if did want start precisely inputs defined in question (variables_of_interest
, groups_of_interest
) use these 2 lines in place of lines marked ## above.
groups <- mget(groups_of_interest) variables <- setnames(nm = variables_of_interest)
Comments
Post a Comment