[datatable-help] Conditional replacement using a single line

Frank S. f_j_rod at hotmail.com
Tue Aug 25 18:40:59 CEST 2015


Thanks Frank for the your ingenious solution!
 
 
 
From: f_j_rod at hotmail.com
To: caneff at gmail.com; eduard.antonyan at gmail.com
Date: Tue, 25 Aug 2015 18:37:45 +0200
CC: datatable-help at lists.r-forge.r-project.org
Subject: Re: [datatable-help] Conditional replacement using a single line




Thank you Eduard and Chris for your very rapid answers!!!
 
Frank S.
 
From: caneff at gmail.com
Date: Tue, 25 Aug 2015 16:27:39 +0000
Subject: Re: [datatable-help] Conditional replacement using a single line
To: eduard.antonyan at gmail.com; f_j_rod at hotmail.com
CC: datatable-help at lists.r-forge.r-project.org

You almost had it right with number 2:
 DT[,value:=ifelse(!duplicated(id),0,2)]

On Tue, Aug 25, 2015 at 12:26 PM Eduard Antonyan <eduard.antonyan at gmail.com> wrote:
DT[, value := c(2, rep(0, .N-1)), by = id]

On Tue, Aug 25, 2015 at 11:17 AM, Frank S. <f_j_rod at hotmail.com> wrote:



Hello everyone,
I ask a question directly linked with other question which I was answered in this list a year ago. Let the data table be:
DT <- data.table(obs=1:7, id=c(1,1,1,4,4,4,4), time=c(3,4,7,5,8,10,15))
 
Now I add a new column, called "value", which contains all zeros except the first observation within each "id" group, which is equal to 2. 
One possible solution I was given is the following two code lines:
> DT[ , value:=0]
> DT[!duplicated(id), value:=2]
 
But I wonder if it is possible to do the same ON A SINGLE CODE LINE. I have tried different options but they doesn't work:
1) DT[ , value:= c(0, 2), by=id]
2) DT[ , value:= ifelse( DT[!duplicated(id)]==T, 2, 0), by=id]
 
Many thanks!
 		 	   		  

_______________________________________________

datatable-help mailing list

datatable-help at lists.r-forge.r-project.org

https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help


_______________________________________________

datatable-help mailing list

datatable-help at lists.r-forge.r-project.org

https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help 		 	   		  

_______________________________________________
datatable-help mailing list
datatable-help at lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20150825/d52c281d/attachment.html>


More information about the datatable-help mailing list