-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.

4

3 回答 3

2

根据文档(参见?sapply),第一个参数 ( X)sapply可以是向量。对向量没有任何限制,说它必须是1:x. 因此,您当前的代码应该正确循环以下值a

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

请注意,您不需要c(a)-a很好:

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

如果由于某种原因您没有与我们沟通,这不起作用,这不是问题,sapply而是您传递给它的函数。

于 2013-10-16T10:55:27.663 回答
2

目前尚不清楚您要达到的目标,但我认为您不需要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
于 2013-10-16T11:01:25.413 回答
1

您是否只想对 中指定的值执行该功能,a否则保留原始值?因为你不提供b我在这里展示另一个例子。

v <- 1:40
a<-c(4,9,20,3,10,30)
sapply(v, function(x) if(x %in% a){x+1} else {x})
于 2013-10-16T11:07:34.160 回答