R data.table multi column recode/sub-assign -


this question has answer here:

let dt data.table:

dt<-data.table(v1=sample(10),                v2=sample(10),                ...                v9=sample(10),) 

is there better/simpler method multicolumn recode/sub-assign this:

dt[v1==1 | v1==7,v1:=na] dt[v2==1 | v2==7,v2:=na] dt[v3==1 | v3==7,v3:=na] dt[v4==1 | v4==7,v4:=na] dt[v5==1 | v5==7,v5:=na] dt[v6==1 | v6==7,v6:=na] dt[v7==1 | v7==7,v7:=na] dt[v8==1 | v8==7,v8:=na] dt[v9==1 | v9==7,v9:=na] 

variable names arbitrary , not have numbers. many columns (vx:vx) , 1 recode pattern (name==1 | name==7, name:=something).

and further, how multicolumn subassign na's else. e.g in data.frame style:

data[,columns][is.na(data[,columns])] <- a_value 

you use set replacing values in multiple columns. based on ?set, fast overhead of [.data.table avoided. use for loop loop on columns , replace values indexed 'i' , 'j' 'na'

 for(j in seq_along(dt)) {       set(dt, i=which(dt[[j]] %in% c(1,7)), j=j, value=na)   } 

edit: included @david arenburg's comments.

data

set.seed(24) dt<-data.table(v1=sample(10), v2= sample(10), v3= sample(10)) 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -