Reputation: 9838
Starting with a simple matrix and a simple function:
numbers <- matrix(c(1:10), nrow = 5, ncol=2)
numbers
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
add <- function(x,y){
sum <- x + y
return(sum)
}
I'd like to add a third column that applies the add function by taking the first two elements of each row.
cheet_sheet <- cbind(numbers, apply(numbers,<MARGIN=first_2_elements_of_row>, add))
The MARGIN seems like a natural place to specify this, but MARGIN=1 is not enough, as it seems to only take one variable from each row while I need two.
Upvotes: 0
Views: 2417
Reputation: 20282
Why not just use mapply
:
> cbind( numbers, mapply( add, numbers[,1], numbers[,2]))
[,1] [,2] [,3]
[1,] 1 6 7
[2,] 2 7 9
[3,] 3 8 11
[4,] 4 9 13
[5,] 5 10 15
Upvotes: 2
Reputation: 47551
With apply you send each selected margin as the first argument to the function. Your function however, requires two arguments. One way to do this without changing your function would be by defining a function of a vector (each row) and sending the first element as first argument and the second element as second:
numbers <- matrix(c(1:10), nrow = 5, ncol=2)
add <- function(x,y){
sum <- x + y
return(sum)
}
cheet_sheet <- cbind(numbers, apply(numbers,1, function(x)add(x[1],x[2])))
However, I guess this is meant purely theoretical? In this case this would be much easier:
cheet_sheet <- cbind(numbers, rowSums(numbers))
Upvotes: 2