results changing between loop, manual entry in R -
i'm running weird issue of looped results being different manually entered ones. need count number of levels in set of variables in data-set. wrote little code turns variable factor, counts number of levels , sets numeric. works fine. when loop across variables, says each variable has 1 level. happened on dataset i'm using , sample data created below. happened when wrote function , used in apply instead of loop. must wrong loop, i'm stuck. thoughts?
here sample data, dataframe 3 variables (x,y,z), 18 observations.
x <- rep(c(1,2,3), 6) y <- rep(c(1,2), 9) z <- rep(c(1,2,3,4,5,6), 3) xyz_df <- as.data.frame(cbind(x,y,z))
so count number of levels each variable-
levelsx <- as.numeric(nlevels(as.factor(xyz_df$x))) levelsy <- as.numeric(nlevels(as.factor(xyz_df$y))) levelsz <- as.numeric(nlevels(as.factor(xyz_df$z)))
the result right- levelsx 3, levelsy 2 , levelsz 6.
but when loop it, changes. created vector values of variables, entered loop, pasting xyz_df$ prefix loop entry-
vars <- c("x", "y", "z") outlist <- list() (a in vars) { levels <- as.numeric(nlevels(as.factor(paste("xyz_df$",a, sep="")))) out <- c(a, levels) outlist <- c(outlist, list(out)) } final <- do.call("rbind", outlist)
when this, levels entry each variable 1.
as said, happened 2 datasets, know it's code. happened apply well. , happened both way did above (pasting xyz_df variable name) , when used attach(xyz_df) , entered variable name.
Comments
Post a Comment