In R, how to replace values in multiple columns with a vector of values equal to the same width? -


i trying replace every row's values in 2 columns vector of length 2. easier show you.

first here data.

set.seed(1234)  x<-data.frame(x=sample(c(0:3), 10, replace=t)) x$ab<-0 #column replaced x$cd<-0 #column replaced 

the data looks this:

   x ab cd 1  0  0  0 2  2  0  0 3  2  0  0 4  2  0  0 5  3  0  0 6  2  0  0 7  0  0  0 8  0  0  0 9  2  0  0 10 2  0  0 

every time x=2 or x=3, want ab=0 , cd=1.

my attempt this:

x[with(x, which(x==2|x==3)), c(2:3)] <- c(0,1) 

which not have intended results:

   x ab cd 1  0  0  0 2  2  0  1 3  2  1  0 4  2  0  1 5  3  1  0 6  2  0  1 7  0  0  0 8  0  0  0 9  2  1  0 10 2  0  1 

can me?

the reason doesn't work want because r stores matrices , arrays in column-major layout. , when assign shorter array longer array, r cycles through shorter array. example if have

x<-rep(0,20) x[1:10]<-c(2,3) 

then end

 [1] 2 3 2 3 2 3 2 3 2 3 0 0 0 0 0 0 0 0 0 0 

what happening in case sub-array x equal 2 or 3 being filled in column-wise cycling through vector c(0,1). don't know of simple way change behavior.

probably easiest thing here fill in columns 1 @ time. or, this:

indices<-with(x, which(x==2|x==3)) x[indices,c(2,3)]<-rep(c(0,1),each=length(indices)) 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -