Zach Fara
Zach Fara

Reputation: 101

replacing values of a few columns in a data.table

I have a data.table like below

dt <- data.table(x = c("name",NA), y = c("2020-12-31T00:00:00.000+00:00",NA), z = c("2019-12-31T00:00:00.000+00:00
",NA))

I want to replace the values of column 2 and 3 in row 2 with values from the the same columns of the first row but only the first 10 characters of its values [substr(.,1:10)]

Upvotes: 0

Views: 76

Answers (1)

akrun
akrun

Reputation: 886938

We could do

library(data.table)
dt[, (2:ncol(dt)) := lapply(.SD, \(x) replace(x, 2,
       substr(first(x), 1, 10))), .SDcols = -1]

Or use set

for(j in 2:ncol(dt)) set(dt, i = 2L, j = j,  substr(first(dt[[j]]), 1, 10))

Upvotes: 2

Related Questions