<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 12pt;
font-family:Calibri
}
--></style></head>
<body class='hmmessage'><div dir='ltr'><p abp="156">Hi all, I'm very novice in data.table management, and I have the following doubt about this data:</p><p abp="158"> </p><p abp="158">> DT <- data.table(obs=1:7, id=c(1,1,1,4,4,4,4), time=c(3,4,7,5,8,10,15))<br abp="165">> DT<br abp="166"><font face="Courier New" abp="167"> obs id time<br abp="168">1: 1 1 3<br abp="169">2: 2 1 4<br abp="170">3: 3 1 7<br abp="171">4: 4 4 5<br abp="172">5: 5 4 8<br abp="173">6: 6 4 10<br abp="174">7: 7 4 15</font></p><p abp="158"> </p><p abp="158">In general, I know that I can select respectively the first and the last observation within "id" group with: </p><p abp="158"> </p><p abp="158"><font face="Courier New" abp="185"><font face="Calibri" abp="186">First observation:</font> <em abp="187">DT[!duplicated(id)] </em></font></p><p abp="158"><font face="Courier New" abp="188"><font face="Calibri" abp="189">Last observation:</font><em abp="190"><font face="Calibri" abp="191"> </font>DT[!duplicated(id, fromLast=T)] </em></font></p><p abp="158"> </p><p abp="158">But, how can I add a new column, called "value", which contains all zeros except:</p><p abp="158">1) The first observation within each "id" group, which is equal to 2</p><p abp="158">2) The last observation within each "id" group, which is equal to 1 ?</p><p abp="158"> </p><p abp="158"><font face="Courier New" abp="175"> obs id time value<br abp="176">1: 1 1 3 2<br abp="177">2: 2 1 4 0<br abp="178">3: 3 1 7 1<br abp="179">4: 4 4 5 2<br abp="180">5: 5 4 8 0<br abp="181">6: 6 4 10 0<br abp="182">7: 7 4 15 1</font></p><p abp="158"><font face="Courier New" abp="192"></font> </p><p abp="158">I've tried with conditionslas, ifelse, etc, but I get an error message. Please, can you help me?</p><p abp="158"> </p><p abp="158">Thanks in advance!!</p><p abp="158"><font face="Courier New" abp="193"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p><p abp="158"><font face="Courier New"></font> </p> </div></body>
</html>