r - Add margins not working -


this code:

x=c(10,20,30,40,50) y=c(17,30,37,50,56) my.tbl=cbind(x,y,x-mean(x),y-mean(y),(x-mean(x))*(y-mean(y)),           (x-mean(x))^2,(y-mean(y))^2) colnames(my.tbl)=c("x","y","x-xbar","y-ybar",                 "(x-xbar)(y-ybar)","(x-xbar)^2","(y-ybar)^2") my.tbl addmargins(my.tbl) 

gives error:

error in array(values, dim = newdim, dimnames = newdimnames) : length of 'dimnames' [1] not equal array extent

can't figure out doing wrong.

using r version 3.1.1 (2014-07-10), rstudio version 0.98.1091

according r help, "table or array. function uses presence of "dim" , "dimnames" attributes of a.". given both rstudent , spotted need dimnames. see below, my.tbl not have rownames. want add rownames following. then, have right outcome.

dimnames(my.tbl)[[1]] <- c("a", "b", "c", "d", "e") addmargins(my.tbl)  class(my.tbl) #[1] "matrix"  str(my.tbl)  #num [1:5, 1:7] 10 20 30 40 50 17 30 37 50 56 ...  #- attr(*, "dimnames")=list of 2  #..$ : null  #..$ : chr [1:7] "x" "y" "x-xbar" "y-ybar" ... 

alternatively, following assign rownames. @ least, working on mac. converting table, rownames.

my.tbl2 <- as.table(my.tbl)  #class(my.tbl2) #[1] "table"  #str(my.tbl2) #table [1:5, 1:7] 10 20 30 40 50 17 30 37 50 56 ... #- attr(*, "dimnames")=list of 2 #..$ : chr [1:5] "a" "b" "c" "d" ... #..$ : chr [1:7] "x" "y" "x-xbar" "y-ybar" ...  addmargins(my.tbl2)  #       x    y x-xbar y-ybar (x-xbar)(y-ybar) (x-xbar)^2 (y-ybar)^2  sum #a     10   17    -20    -21              420        400        441 1247 #b     20   30    -10     -8               80        100         64  276 #c     30   37      0     -1                0          0          1   67 #d     40   50     10     12              120        100        144  476 #e     50   56     20     18              360        400        324 1228 #sum  150  190      0      0              980       1000        974 3294 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -