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?
Asked
Active
Viewed 223 times
0

monte
- 1,482
- 1
- 10
- 26

Hannah Harder
- 67
- 10
-
2Hi 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 Answers
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,203
- 1
- 7
- 24
-
That worked perfectly!! Thank you so much. Will this extend to being able to adjust individual rows and columns together? Like if I want to subtract a constant number from rows 18-24 in the 3rd column, then I would do something like this: ``` top_secret[18:24,3] <- top_secret[18:24, 3]-100] ``` ? – Hannah Harder Jul 08 '20 at 18:27
-
-
Hmm I tried to format my code but I guess I did it wrong. Sorry I'm really new to this. – Hannah Harder Jul 08 '20 at 18:28
-
this should work: `top_secret[18:24,3] <- top_secret[18:24, 3] - 100` or `m[1:2,1] <- m[1:2,1] - 100` in my example – slava-kohut Jul 08 '20 at 18:30
-
@HannahHarder No problem, I am here to help. Consider upvoting or accepting if you liked the answer. – slava-kohut Jul 08 '20 at 19:58
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
- 874,273
- 37
- 540
- 662