Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding every second column in a matrix starting from the 3rd column in r

Tags:

r

I would like to add the values of each row for every second column in a matrix of the following form:

1  1  100 2 104 4 200
2  1  100 2 103 3 203
3  1  100 3 101 3 304
4  1  100 4 105 2 201

Here I would like to add the 3rd column and then every second one, producing the following output:

404
406
505
406

Can this be done without a for loop?

like image 212
user1723765 Avatar asked Dec 15 '22 15:12

user1723765


2 Answers

Assuming that your data frame is named df.

 apply(df,1,function(x) sum(x[seq(3,length(x),2)]))
[1] 404 406 505 406
like image 71
Didzis Elferts Avatar answered Mar 30 '23 00:03

Didzis Elferts


You can do:

rowSums(df[,-c(1,2)][, c(TRUE, FALSE)])
# [1] 404 406 505 406

where [, -c(1,2)] discards the first two columns and [, c(TRUE, FALSE)] keeps every other column.

like image 23
flodel Avatar answered Mar 29 '23 23:03

flodel