0

I'm a complete R novice, and I'm really struggling on this problem. I need to take a vector, evens, and subtract it from the first column of a matrix, top_secret. I tried to call up only that column using top_secret[,1] and subtract the vector from that, but then it only returns the column. Is there a way to do this inside the matrix so that I can continue to manipulate the matrix without creating a bunch of separate columns?

monte
  • 1,145
  • 5
  • 18
  • 2
    Hi Hannah, it will be much easier to help if you provide at least a sample of your data with `dput(top_secret)` and `dput(evens)`. If your data really is *top secret* you can make up something that has a similar structure. Ideally, you would also provide your expected output. Please surround the output of `dput` with three backticks (```) for better formatting. See [How to make a reproducible example](https://stackoverflow.com/questions/5963269/) for more info. – Ian Campbell Jul 08 '20 at 17:54
  • Sorry about that. This is my first post here and I've never done any R work before. I tried to format my code in another comment but it didn't work. I'll try and figure this out for my next question. – Hannah Harder Jul 08 '20 at 18:30

2 Answers2

2

Sure, you can. Here is an example:

m <- matrix(c(1,2,3,4),4,4, byrow = TRUE)

> m
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
[3,]    1    2    3    4
[4,]    1    2    3    4

m[,4] <- m[,4] - c(5,5,5,5)

which gives:

> m
     [,1] [,2] [,3] [,4]
[1,]    1    2    3   -1
[2,]    1    2    3   -1
[3,]    1    2    3   -1
[4,]    1    2    3   -1
slava-kohut
  • 4,065
  • 1
  • 5
  • 22
0

Or another option is replace

replace(m, cbind(seq_len(nrow(m)), 4), m[,4] - 5)

data

m <- matrix(c(1,2,3,4),4,4, byrow = TRUE)
akrun
  • 789,025
  • 32
  • 460
  • 575