0

I want to do the following:

#choosing one column called "z" from select 
select<-read.table(file='dane.txt', header=TRUE)
n=select$z

#defining f function
f<-function(redshift) {
  0.2*(sqrt(0.3*((1+redshift)^3)+0.7*((1+redshift)^2)+1))^(-1)
}

 # for all values from column "z" I want to calculate the integral from 0 up to value from column "z"
for(i in n){
  int[i]<-integrate(f(i),0,i)
}

For all values from column "z" I want to calculate the integral from 0 up to value from column "z" and I want to save my results for each row from file, under the name int. Why it did't work? Right now it gives me the error: "Error in match.fun(f) : 'f(i)' is not a function, character or symbol" . Please, help.

  • `f` is a function. What do you think `f[i]` is doing? Are you trying to call the function? That would be done with `f(i)`. But It looks like you just want to pass the whole function to integrate: `integrate(f,0,i)`. Also, where is `int` coming from? Please try to provide [reproducible examples](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and clearly indicate the desired output. – MrFlick Jun 08 '15 at 20:04
  • Yes, I want to call the function. In first attempt I had int[i]<-integrate(f(i),0,i), but it also did't work. I put here my last attempt with f[i]. I want to save my results under the name of "int". I want to calculate integrate(f,0,i), and for all "i" from column "z" in my file, I want to save the results. For example, for first value from n (let the value be 0.1): I want to calculate integral like this: integrate(f(0.1),0,0.1). – Agnieszka Kurcz Jun 08 '15 at 20:31

1 Answers1

0

Since there is no example data I assume some for which your function is defined:

n = as.vector(runif(n=100, min=-3, max=10))
num.obs = length(n)

define your function as you did:

f<-function(redshift) {
  0.2*(sqrt(0.3*((1+redshift)^3)+0.7*((1+redshift)^2)+1))^(-1)
}

the way you want to assign values to int you have to initialize it first and do the iteration over the index, not the value of n. integrate gives you a list but I guess you are interested in the value.

int=matrix(NA, nrow=num.obs, ncol=1)
for(i in 1:num.obs){
  int[i]=integrate(f,0,n[i])$value
}
mts
  • 2,160
  • 2
  • 24
  • 34