0

I am looking for a way to add 3 values in 3 different columns to a matrix based on the value in an existing column.

experiment = rbind(1,1,1,2,2,2,3,3,3)
newColumns = matrix(NA,dim(experiment)[1],3) # make 3 columns of length experiment filled with NA
experiment = cbind(experiment,newColumns) # add new columns to the experimental data
experiment = data.frame(experiment)    
experiment[experiment[,1]==1,2:4] = cbind(0,1,2) # add 3 columns at once
experiment$new[experiment[,1]==2] = 5 # add a single column
print(experiment)

  X1 X2 X3 X4 new
1  1  0  0  0  NA
2  1  1  1  1  NA
3  1  2  2  2  NA
4  2 NA NA NA   5
5  2 NA NA NA   5
6  2 NA NA NA   5
7  3 NA NA NA  NA
8  3 NA NA NA  NA
9  3 NA NA NA  NA

this, however, fills the new columns the wrong way. I want column 2 to be all 0's, column 3 to be all 1's and column 4 to be all 3's.

I know I can do it 1 column at a time, but my real dataset is quit large so that isn't my preferred solution. I would like to be able to easily add more columns just by making the range of columns larger and adding values to the 3 values in the example

0

1 Answer 1

1

Instead of this:

experiment[experiment[,1]==1,2:4] = cbind(0,1,2) # add 3 columns at once

Try this:

experiment[experiment[,1] == 1, 2:4] <- rep(c(0:2), each=3)

The problem is that you've provided 3 values (0,1,2) to fill 9 entries. The values are by default filled column-wise. So, the first column is filled with 0, 1, 2 and then the values get recycled. So, it goes again 0,1,2 and 0,1,2. Since you want 0,0,0,1,1,1,2,2,2, you should explicitly generate using rep(0:2, each=3) (the each does the task of generating the data shown just above).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.