r - Partially update row in data.table -


let's assume have following data.table:

> dt <- as.data.table(mtcars) > head(dt)     mpg cyl disp  hp drat    wt  qsec vs gear carb 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 

i update columns cyl:wt of first row vector vec <- 1:5 such that:

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

i tried:

dt[1, .sd := vec, .sdcols = cyl:wt]      # fails dt[1, (.sd) := .(vec), .sdcols = cyl:wt] # fails 

the .sd cannot used on lhs of := assigning. need character vector. option set

j1 <- which(names(dt) %in% c('cyl', 'wt')) j2 <- j1[1]:j1[2] for(j in seq_along(j2)){    set(dt, = 1, j = j2[j], value = vec[j])  }  head(dt) #    mpg cyl disp  hp drat    wt  qsec vs gear carb #1: 21.0   1    2   3 4.00 5.000 16.46  0  1    4    4 #2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 #3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 #4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 #5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 #6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 

note: have careful while updating values , should check class of original columns can have numeric/integer changes


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -