简体   繁体   中英

if first then update in a new column in R

Suppose if I have a dataset dt

dt <- as.data.table(mtcars)

For the first row by 'cyl' variable, I want to update a new column test to the value of 'qsec' variable. Also I don't want to drop other observations but instead the value pf test to zero for them.

The below code gives the first row. But I am confused on how to update a column and retain everything

dt[order(cyl), .SD[c(1)], by=cyl]

Example of needed output

    mpg cyl disp  hp drat    wt  qsec vs am gear carb  test
1: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 18.61
2: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 16.46
3: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  0.00
4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1  0.00
5: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1  0.00
6: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 17.02

NOTE : It is for a big data so would really appreciate if there is an efficient code that works faster.

We can do this with rowid without grouping

library(data.table)
dt[, test := (rowid(cyl) == 1) * qsec]

-output

head(dt, 8)
#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb  test
#1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 16.46
#2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  0.00
#3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 18.61
#4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1  0.00
#5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 17.02
#6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1  0.00
#7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4  0.00
#8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2  0.00

Or another option is .I which is very fast

dt[, test := 0] # // create a column of 0's
i1 <- dt[, .I[1], cyl]$V1 # // get the index of the first element for each cyl
dt[i1, test := qsec] # // specify it in i and update the test 

You can use replace :

library(data.table)
dt <- as.data.table(mtcars)
dt[, test := replace(qsec, -1, 0), cyl]
dt

#     mpg cyl  disp  hp drat    wt  qsec vs am gear carb  test
# 1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 16.46
# 2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  0.00
# 3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 18.61
# 4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1  0.00
# 5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 17.02
# 6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1  0.00
# 7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4  0.00
# 8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2  0.00
#...
#...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM