2014-06-12 60 views
0

尝试创建一个函数,该函数将生成累积热单位所需的天数列表/矢量。在函数中使用矢量索引

Day<-c(1:10) 
min1<-c(0.70,1.45,2.22,2.98,3.75,4.50,5.02,5.34,5.61,5.81) 
data<-as.data.frame(cbind(Day,min1)) 

下面的函数正确地对输出数据$ MIN1超过2天:

days.till<-function (x) min(data$Day[data$min1>=x]) 
days.till(2) 

但是,如果我尝试使用一些x值,我得到一个错误。

days.till(2:4) 
[1] 4 
Warning message: 
In data$min1 >= x : 
longer object length is not a multiple of shorter object length 

以下策略返回相同的错误:

days.till(c(2:4)) 

days.till<-function (x=2:4) min(data$Day[data$min1>=x]) 

我已经在其他简单的功能使用多个输入值没有问题,所以我担心在函数中向量索引导致了问题。任何帮助将不胜感激。

+0

你可以换你的函数在'Vectorize'中:'Vectorize(days.till)(2:4)' –

+0

顺便说一句,检查'findInterval',因为在这种情况下它会快很多:'findInterval(2:4,data $ min1)+ 1 ' –

+0

@alexis_laz你应该添加这个作为答案(与microbenchmark结果) - 它肯定快得多,就像其他发布的解决方案一样简单 – josliber

回答

1

您可以使用sapply来计算通过矢量每个元素所需的值:

days.till <- function(x) sapply(x, function(y) min(data$Day[data$min1>=y])) 
days.till(2:4) 
# [1] 3 5 6 
0
Day<-c(1:10) 
min1<-c(0.70,1.45,2.22,2.98,3.75,4.50,5.02,5.34,5.61,5.81) 
mydata<-as.data.frame(cbind(Day,min1)) 

days.till <- function(x,data=mydata) { 
    if (length(x)==1){ 
    return(min(data$Day[data$min1>=x])) 
    } else if (length(x)>1) { 
    return(lapply(x,days.till,data=data)) 
    } 
} 

## > days.till(2) 
## [1] 3 
## > days.till(2:4) 
## [[1]] 
## [1] 3 

## [[2]] 
## [1] 5 

## [[3]] 
## [1] 6 
0

这是你的函数的修改版本:

days.till <- function(thresh) 
    with(data, Day[sapply(thresh, function(x) which(min1 >= x)[1])]) 

days.till(2:4) 
# [1] 3 5 6