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!
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. ...
iterator() method every() methods in that it can be used to access item information from the table.
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]
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With