Monday 15 June 2015

data.table - R how tocheck if a data table column is all zeros -



data.table - R how tocheck if a data table column is all zeros -

i remove columns have zeros. but, of columns appear have non numeric values. how can remove non numeric columns, , columns zeros. helpful if non numeric column name printed, or column number, can determine if ok remove column.

here's i'm trying, doesn't work when info table has non numeric values.

removecolsallzeros = function(ddt) { m <- as.matrix(ddt) # isnumericcollist <- lapply(1:ncol(m), function(ii,mm){is.numeric(mm[,ii])}, mm=m) # indexnonnumericcols <- which(!unlist(isnumericcollist)) mnz <- m[, colsums(abs(m),na.rm = true) != 0] return(mnz) }

here's simple function can applied columns in info frame, returning ones numeric , not zero:

# false info dat = data.frame(x=rnorm(5), y=rep(0,5), z=sample(c(1,0),5,replace=true), w=sample(letters[1:3],5,replace=true), stringsasfactors=false) dat x y z w 1 0.5450570 0 0 b 2 0.5292899 0 0 b 3 -0.2142306 0 1 c 4 -0.7246841 0 0 c 5 -0.7567683 0 1 # remove columns zeros or not numeric dat[, !sapply(names(dat), function(col) {all(dat[,col]==0) | !is.numeric(dat[,col])})] x z 1 0.5450570 0 2 0.5292899 0 3 -0.2142306 1 4 -0.7246841 0 5 -0.7567683 1

to unpack this, function checks, single column of dat, whether has zeros or not numeric. sapply "applies" function every column in info frame, returning logical vector true columns of dat zeros or non-numeric, , false columns numeric , not zeros. ! ("not") before sapply reverses false , true values:

!sapply(names(dat), function(col) { all(dat[, col]==0) | !is.numeric(dat[, col]) }) x y z w true false true false

then utilize logical vector homecoming columns of dat true.

dat[ , c(true, false, true, false)] x z 1 0.5450570 0 2 0.5292899 0 3 -0.2142306 1 4 -0.7246841 0 5 -0.7567683 1

finally, check non-numeric columns removed, following, homecoming non-numeric columns:

dat[, sapply(names(dat), function(col) {!is.numeric(dat[,col])})]

r data.table zero

No comments:

Post a Comment