-1

I have a matrix 320X64 and I want to modify the 64 variables so that the first 8 are equal to 0 and the last 56 equal to 1.

I tried the repeat function :

pen.vect<-(rep(0,8),rep(1,56)) 
penalty.factor<-pen.vect 

but it's not working

Thank you :)

WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
  • 3
    For an existing matrix named myMat with dimensions 320 X 64, `myMat[] <- rep(c(0, 1), c(8, 56) * 320)`. To build from scratch: `myMat <- matrix(rep(c(0, 1), c(8, 56) * 320), 320)`. – lmo Dec 09 '16 at 18:41

1 Answers1

0

You can change between matrices and data frames easily. Working with a data frame will allow you to accomplish this easier with bracket notation:

bm <- as.data.frame(B)   # assuming your matrix is called "B"
bm[,1:8] <- 0
bm[,9:56] <- 1
B2 <- as.matrix(bm)

Here's a full, working example with dummy data:

B = matrix(c(2:65), nrow=320, ncol=64) # Create a matrix with dummy data
bm <- as.data.frame(B)                 # Change it to a data frame
bm[,1:8] <- 0                          # Change each row in the first 8 columns to 0
bm[,9:56] <- 1                         # Change the rest to 1
B2 <- as.matrix(bm)                    # Change the data back to a matrix

Also, take a look at this post for how to properly post an R question. I'm honestly shocked your question hasn't been deleted or flagged yet. R on SO can be brutal.

Community
  • 1
  • 1
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129