[datatable-help] How to replace values in data.table conditionally

Matt Dowle mdowle at mdowle.plus.com
Thu Mar 13 18:47:22 CET 2014


On 13/03/14 14:48, Manabu Sakamoto wrote:
> Dear list
>
> I'm trying to access values within a data.table column by matching to 
> elements in a vector and replacing with corresponding elements in a 
> second vector. But I want to loop through specific column names also 
> stored as a character vector.
> So something like:
>
> DT<- data.table(A=seq(1:10),B=seq(1:10),C=seq(1:10))
>
> cnm <- c("A", "B", "C")
> before <- c(4, 5, 6)
> after <- c(3, 7, 8)
>
> nm <- cnm[i]
> bfr <- before[i]
> afr <- after[i]
>
> DT[nm==bfr, nm:=afr]
>
> I'm sure this is completely wrong because it didn't work.
> So does anyone know how to correctly do this data.table solution?

DT[get(nm)==bfr, (nm):=afr]

or

set(DT, i=DT[[nm]]==bfr, j=nm, value=afr)

I prefer the first way but if you're looping through many columns (say 
1,000+) then using set() should be faster, see ?set.

HTH, Matt

>
> Many thanks,
> Manabu
>
>
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20140313/8fc07051/attachment-0001.html>


More information about the datatable-help mailing list