Kersijus
Kersijus

Reputation: 87

Create vector selecting values from two different vectors

Currently, this code works to do what I want to do where dx$res is a vector selecting values from dx$val1 or dx$val2 depending on value of dx$x0.

x0<-c(1,2,1,2,2,1)
val1<-c(8,6,4,5,3,2)
val2<-c(4,8,6,7,9,5)
dx<-data.frame(x0,val1,val2)
dx$res<-(dx$x0==1)*dx$val1+(dx$x0==2)*dx$val2

I would like to know if there were more elegant methods to do this like using apply function.

Upvotes: 1

Views: 48

Answers (1)

akrun
akrun

Reputation: 887183

One option is model.matrix with rowSums. It is also more general for 'n' number of distinct elements in the 'x0' column.

dx$res <- rowSums(dx[-1]*model.matrix(~ factor(x0) - 1 , dx))
dx$res
#[1] 8 8 4 7 9 2

Upvotes: 1

Related Questions