efz
efz

Reputation: 435

how to replace values in data table based on another table

I have a data.table with 83 columns called growthcheck. The vector flag4issues contains a subset of 21 column names of growthcheck. flag4issues is a character vector.

test is another vector having dimension 3 by 21. I'm debugging a code where the line

growthcheck[1:3, flag4issues] <- test 

throws an error.

I tried with tranforming test to data.table, do a loop, but nothing works. Any idea?

dput(growthcheck[1:5,flag4issues]), test and flag4issues can be retrieved here

Upvotes: 1

Views: 159

Answers (1)

akrun
akrun

Reputation: 886938

The data.table syntax would be to specify the row index in i (1:3), assign the data.frame ('test') to the columns specified. As the columns of 'growthcheck' are numeric class and the 'test' are character (matrix), need to convert the class before doing the assignment

library(data.table)
growthcheck <- growthcheck[, lapply(.SD, as.character)]
growthcheck[1:3, (flag4issues) := as.data.frame(test)]

-output

growthcheck[1:3, 1:2]
   Country
1: Austria
2: Austria
3: Belgium
                                                                                                               Obs
1:  3.A.4.3 - Population (POP, Deer): Irregularities in the time series have been been identified. Years flagged: 
2:  3.A.4.3 - Population (POP, Deer): Irregularities in the time series have been been identified. Years flagged: 
3: 3.A.4.4 - Population (POP, Goats): Irregularities in the time series have been been identified. Years flagged: 

Upvotes: 1

Related Questions