-5

I would like to have an sapply() statement of the following form:

a <- c(4, 9, 20, 3, 10, 30)
sapply(c(a), function(x) b[x,2] - b[x,1])

Normally instead of c(a) I would have 1:x, however now I would like to go through only the values specified in a. Is this possible?

Update: The point is not what goes after function(x) - that is only intended as an example.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
upabove
  • 1,057
  • 3
  • 18
  • 29

3 Answers3

2

According to the documentation (see ?sapply), the first argument (X) to sapply can be a vector. There is no restriction on the vector saying it has to be of the form 1:x. So your current code should loop correctly over the values of a:

sapply(c(a), function(x) b[x,2]-b[x,1]) 

Note, that you don't need c(a) - just a is fine:

sapply(a, function(x) b[x,2]-b[x,1])

If for some reason you did not communicate to us this does not work, it is not a problem with sapply but with the function you are passing to it.

flodel
  • 87,577
  • 21
  • 185
  • 223
csgillespie
  • 59,189
  • 14
  • 150
  • 185
2

It isn't very clear what you are trying to achieve, but I don't think that you need sapply.

a <- c(4, 9, 20, 3, 10, 30)
b <- data.frame(x = 1:30, y = sqrt(1:30))
b[a, 2] - b[a, 1]
## [1]  -2.000000  -6.000000 -15.527864  -1.267949  -6.837722 -24.522774
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • all I want is sapply to use as 'x' the values specified in 'a' instead of iterating through a 1:n interval – upabove Oct 16 '13 at 11:02
1

Do you want to perform the function only on the values specified in a but keep the original values otherwise? Because you don't provide b I show another example here.

v <- 1:40
a<-c(4,9,20,3,10,30)
sapply(v, function(x) if(x %in% a){x+1} else {x})
Jonas Tundo
  • 6,137
  • 2
  • 35
  • 45
  • Yeah, I think you are right (that they are after values and not indices). However, they coincide in your example...`identical(v,seq_along(v))` – Frank Oct 16 '13 at 15:53
  • 1
    Yes, but that wouldn't matter for the function. You can replace `v` with another vector. – Jonas Tundo Oct 17 '13 at 06:22