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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With