Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Data.Table Multiple Assignment IfElse

Tags:

r

data.table

data1=data.frame(Year=c(1,1,1,2,2,2,3,3,3),
"Group=c('A','A','A','B','B','B','C','C','C'),
"A=c(5,6,7,10,9,6,10,7,10),
"B=c(8,10,5,6,9,8,9,5,8),
"C=c(7,9,5,5,8,7,9,5,10))



data2=data.frame(Year=c(1,1,1,2,2,2,3,3,3),
"Group=c('A','A','A','B','B','B','C','C','C'),
"A=c(5,6,7,10,9,6,0,0,0),
"B=c(8,10,5,6,9,8,0,0,0),
"C=c(7,9,5,5,8,7,-99,-99,-99))

I have 'data1' and wish for 'data2' by using fifelse from data.table. The rule is, if Group = 'C', then columns 'A' and 'B' equal to zero and column 'C' equals to -99.

like image 852
bvowe Avatar asked Nov 25 '25 05:11

bvowe


1 Answers

Using conditional replacement in data.table,

data.table::setDT(data1)
data1[Group == "C",`:=`(A = 0, B = 0, C = -99)]

Note that the final dataframe is data1 (:= updates by reference), not data2

like image 60
linog Avatar answered Nov 27 '25 20:11

linog



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!