Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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

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})
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top