Hello everyone!
I am a newbie to R coding and coding in general. I only have some experience with a bit C coding.
I somehow can't find a solution for my problem.
I want to calculate the mean of a distribution function, it is F(x)= 0, for x<0,
F(x)= x^2, for 0<=x<=1, and else (x>1) F(x)=1.
The mean of it is defined by an integral over the single intervals with F'(x)*x as integrand for each interval of x.
My idea to solve it, was to implement the function using a if/else loop and store the arguments of the function in a vector.
To calculate the mean, I'd then derive the vector's single elements, store it in a new vector and multiply it with x.
Then i'd integrate this.
Problem is the output: although i defined the x- dependent parts of the function using 'function(x)' , the output of the vector will tell me, that the x- dependent part of the function body is "recognized" as language and not as variable.
So the symbolic derivation of it will give me... something that is mathematically not right in the context.
Also, how to multiply and call the vectorelements later?
Could i use sapply then?
Please don't judge me, i really tried it for days and i ran out of ideas.
my latest idea to implement it, was:
library(Deriv)
arg_df <- c(function(x) {x^2} , 1, 0)
a_f<- c(function(x){ Deriv(arg_df[[1]], "x")}, Deriv(arg_df[[2]], "x") , Deriv(arg_df[[3]], "x"))
b<- c(function(x) {a_f[[1]]*x}, function(x) {a_f[[2]]*x}, function(x) {a_f[[3]]*x})
b
The 'original' code looks something like this (with different chunks, where i tried different ideas..)
if (!requireNamespace("numDeriv", quietly = TRUE)) {
install.packages("numDeriv")
}
library(numDeriv)
if (!requireNamespace("Deriv", quietly = TRUE)) {
install.packages("Deriv")
}
library(Deriv)
arg_f <- function(x) c(x^2 , 1, 0)
df<- Deriv(arg_f, "x")
print(df)
x<- runif(1, min=-3, max=3)
arg_f <- c(x^2 , 1, 0)
f <- function(x) {
if (x >= 0 & x <= 1) {
result<- arg_f[1]
# return(arg_f[1])
} else if (x > 1) {
result<- arg_f[2]
# return( arg_f[2] )
} else {
result<- arg_f[3]
# return(arg_f[3])
}
cat(result, "\n")
return(result)
}
f(x)
arg_f <- function(x) c(x^2 , 1, 0)
print(arg_f)
a_f <- function(x) {
df <- function(x) Deriv(arg_f, "x")
derivatives <- df(x)
result <- list(derivatives = derivatives, x = x)
print(result)
return(result)
}
arg_f <- function(x) c(x^2 , 1, 0)
print(arg_f)
a_f<-function(x) {
df<- Deriv(arg_f, "x")
return(df)
}
print(a_f(x))
d<- a_f(x)
print(d)
str(d)
list(d)
#just need to index a_f(x), don't know why r is not accepting it??
d<- function(x){
a_f[[1]]
}
print(d)
#i<- c(1,2,3), maybe indexing it with a index vector??
intgr <- function(x,i) sapply(x, function(x) x * function(x) a_f[i])
#intgr<- function(x,a_f) (x*a_f(x))
result <- function(x,a_f) intgr(x, a_f)
result(x,a_f)
mean_f <- function(x) {
a<- integrate(intgr, lower = -Inf, upper = 0 )
b<- integrate( intgr , lower = 1, upper = Inf)
c<- integrate()
}
return(a+b+c)