Then what about:
fun<-function(a,b,c,data) {
ifelse(data > c, (a*(data-c)^0.5)+(b*(data-c)), 0)
}
y=c(100,210,320,130,170,120,220,90,55,45)
fun(1,0.2,150,data=y)
> fun(1,0.2,150,data=y)
[1] 0.00 77471.67 130418.05 0.00 44725.36 0.00 83680.00
[8] 0.00 0
Try this -- this uses the vectorization which you need to read up on
in the Intro to R:
> #set the function
> fun<-function(a,b,c,data)
+ {
+ N <- numeric(length(data)) # initialize to zero
+ indx <- data > c # determine which data is greater than c
+ N[indx] <- (a * (data[indx] - c) ^ 0.5) + (b
thank you. yes I want to loop over the elements of the data. I want the
output to be corresponded to the input by unchanging index. at the same
time, the data that is more than c value should follow the
function (a*(data-c)^0.5)+(b*(data-c), and the rest (same or less than c)
should return a zero.
N=as.vector()
This doesn't mean anything in R: you can read the help using
?as.vector
to see what the required arguments are.
Do you want to loop over the elements of data? That's not what your
loop is doing. Instead it is looping over each element of the sequence
from the min to the max *value*
Hi all,
I'm trying to create a function where it can process a vector and also give
a vector output accordingly
#input: a,b anc c are constants, data is the vector
#set the function
fun<-function(a,b,c,data)
{
N=as.vector()
for (i in min(data):max(data)){
if(i>c){
N<-(a*(i-c)^0.5)+(b*(i-c))}
else
5 matches
Mail list logo