neojin
neojin

Reputation: 11

how to subtract certain column in R?

I would like to subtract one certain column in R? How to do it?

vec <- 1:20
mat <- matrix(vec,ncol=4)

mat
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

for example, i would like to calculate the difference between 1th and 4th, 2th and 4th, 3th and 4th

the results:

M1 <- mat[,1]-mat[,4]

M2 <- mat[,2]-mat[,4]

M3 <- mat[,3]-mat[,4]
nmat <- data.frame(M1,M2,M3)
nmat

   M1  M2 M3
1 -15 -10 -5
2 -15 -10 -5
3 -15 -10 -5
4 -15 -10 -5
5 -15 -10 -5

Upvotes: 0

Views: 6905

Answers (2)

Sander Van der Zeeuw
Sander Van der Zeeuw

Reputation: 1092

You can also use an lapply function

lapply(mat[[1]], function(k){return(mat[, 1:3] - mat[, 4])})

which gives you the opportunity to calculate per list.

and gives the following output: 
[[1]]
     [,1] [,2] [,3]
[1,]  -15  -10   -5
[2,]  -15  -10   -5
[3,]  -15  -10   -5
[4,]  -15  -10   -5
[5,]  -15  -10   -5

every time you change the mat[[1]] to for example [[2]]. The 'lapply' function will calculate for another list. If you just put mat It will calculate for every list.

Upvotes: 1

CHP
CHP

Reputation: 17189

try

vec <- 1:20
mat <- matrix(vec, ncol = 4)
mat[, 1:3] - mat[, 4]
##      [,1] [,2] [,3]
## [1,]  -15  -10   -5
## [2,]  -15  -10   -5
## [3,]  -15  -10   -5
## [4,]  -15  -10   -5
## [5,]  -15  -10   -5

PS : This is very basic in R, perhaps you should look at some basic R tutorials listed here. https://stackoverflow.com/tags/r/info

Upvotes: 5

Related Questions