kray
kray

Reputation: 25

looking for a more "data.table-ish" way to add a new column based on conditions from another

I can add a conditional column like this:

dt$newcol <- ifelse(dt4$doy > 150 & dt4$doy < 280, 1, 0)

which adds the new column "newcol" to the data table "dt" and fills newcol with a 1 if doy is greater than 160 AND less than 280, otherwise fills with 0s.

I have been trying to get used to the data table syntax and I am wondering how to make use of the := oporator to do this in a more data table style?

Thanks in advance

Upvotes: 0

Views: 74

Answers (1)

akrun
akrun

Reputation: 887088

You could try

 library(data.table)
 dt4[,newcol:=(doy >150 & doy <280)+0L]
 head(dt4)
 #  doy         val newcol
 #1: 103 -1.35466363      0
 #2:  79 -0.96080882      0
 #3: 247  0.22495434      1
 #4: 182 -0.12316046      1
 #5: 232  0.00104102      1
 #6: 323 -0.57124325      0

Or you could use as.integer as commented by @Arun

 dt4[,newcol:= as.integer(doy>150 & doy < 280)]

data

 set.seed(24)
 dt4 <- data.table(doy=sample(1:350, 150, replace=TRUE), val=rnorm(150) )

Upvotes: 3

Related Questions