0

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.

Milktrader
  • 9,278
  • 12
  • 51
  • 69

2 Answers2

2

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))
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • Excellent! Yes, this is a theoretical example. I'm planning to pass strings to a bit more complicated function that will return a numerical value. I simply was unable to put your answer together from the examples in help(apply). – Milktrader Feb 17 '11 at 03:13
  • 1
    Put a `browser()` call inside your function and "look around" with `str` and kin. – Roman Luštrik Feb 17 '11 at 09:33
  • @Roman I'm intrigued. help(browser) suggests its a sort of debugging function. Do you have an example usage? – Milktrader Feb 17 '11 at 11:35
  • This should get you started: http://stackoverflow.com/questions/1169480/debugging-tools-for-the-r-language – Roman Luštrik Feb 17 '11 at 12:15
  • +1 for `browser()`, up till now I debug by manually running functions up to a certain point:) – Sacha Epskamp Feb 17 '11 at 12:33
2

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
Prasad Chalasani
  • 19,912
  • 7
  • 51
  • 73