Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a simple loop with data.table

Tags:

r

data.table

I want to do a simple loop using data.table. I have 20 dichotomous (0,1) variables (from var_1 to var_20) and I would like to do a loop for this:

dat[var_1==1, newvar:=1]
dat[var_2==1, newvar:=2]
dat[var_3==1, newvar:=3]
...
dat[var_20==1, newvar:=21]

My main problem is I don't know how specify i (i.e. var_1==1, var_2==2...) using a loop. Below a short example:

var_1  <- c(1, rep(0,9))
var_2  <- c(0,1, rep(0,8))
var_3  <- c(0,0,1, rep(0,7))
dat  <- data.table(var_1, var_2, var_3)

dat[var_1==1, newvar:=1]
dat[var_2==1, newvar:=2]
dat[var_3==1, newvar:=3]

Any ideas about how to do this with a loop? Thanks!

like image 336
sdaza Avatar asked Dec 02 '12 04:12

sdaza


People also ask

What is a simple data table?

data tables have up to one row and up to one column of header cells. Figure 5 shows an example of a simple table used in the literature. It is easy to observe that the first row is the only row of header cells while there is no respective column of headers. ...

Which branching technique is used to iterate all items in a data table?

iterator() method every() methods in that it can be used to access item information from the table.


2 Answers

To take advantage of data.table class it is better to set key.

dat[ ,newvar:= NA_integer_]
for(i in ncol(dat)) {
 setkeyv(dat, names(dat)[i])
 dat[J(1), newvar:=i]
}
like image 121
Wojciech Sobala Avatar answered Oct 20 '22 11:10

Wojciech Sobala


Something like this will work.

nams <- names(dat)
for(n in seq_along(nams)){
  nam <- nams[n] 
  char <- sprintf('%s==1',nam)
  dat[eval(parse(text=char)), newvar := n]
}
dat
var_1 var_2 var_3 newvar
1:     1     0     0      1
2:     0     1     0      2
3:     0     0     1      3
4:     0     0     0     NA
5:     0     0     0     NA
6:     0     0     0     NA
7:     0     0     0     NA
8:     0     0     0     NA
9:     0     0     0     NA
10:    0     0     0     NA
like image 36
mnel Avatar answered Oct 20 '22 12:10

mnel