Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace subset of data table with other data table

Tags:

r

data.table

I feel a bit silly for this question, but I only want to something which I know how to do with a data.frame, but I have not yet found a nice way to do it in R. All other similar questions seem way more complicated for what I have in mind. I simply want to replace a subset of a data.table with another data.table only based on an row index and choosing some columns.

MWE follows

x.df <- data.frame(a=c(1,2,3),
               b=c(2,NA,NA), 
               c=c(3,NA,NA))
x.dt <- data.table(x.df)
x.df.replace<- data.frame(b=c(10,11), c=c(22,21))
x.dt.replace<- data.table(x.df.replace)

This works like a charm in data Frame

x.df[is.na(x.df$b),2:3]<-x.df.replace

On the other hand I would like to call the columns by name and I only know how to replace each column individually, but not jointly

x.dt[is.na(b),]
x.dt[is.na(b),c:=x.dt.replace[,c]]
x.dt[is.na(b),b:=x.dt.replace[,b]]
x.dt[is.na(b), list(b,c)]<-x.dt.replace
x.dt[is.na(b), list(b,c):=x.dt.replace]
like image 731
Max M Avatar asked Oct 19 '25 03:10

Max M


1 Answers

I was having the same issue and I came across this question with no answer. The comments above helped me to find the solution to my problem, so I decided to post it here. May simply be a difference between data.table versions (I am using version 1.11.8), since this is relatively old question.

The solution uses a () instead of a .() or a list() to declare the column names to be replaced:

colunas <- c("b","c")
x.dt[is.na(b), (colunas) := x.dt.replace]

Hope this is useful

like image 194
R. Lima Avatar answered Oct 20 '25 17:10

R. Lima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!