I want to calculate the log return of data . I define a function and want to load the data. but system always mentions second factor is missing. Otherwise it just calculate the log of row number.
#read data
data <- read.csv(file="E:/Lect-1-TradingTS.csv",header=TRUE)
mode(data)
p<-data["Price"]
#func1
func1 <- function(x1,x2)
{
result <- log(x2)-log(x1)
return(result)
}
#calculate log return
log_return<-vector(mode="numeric", length=(nrow(data)-1))
for(i in 2:nrow(p))
{
log_return[i-1] <- func1(p[(i-1):i])
}
Error in func1(p[(i - 1):i]) : argument "x2" is missing, with no default
Your function func1 was defined to accept two arguments, but you are passing it a single argument: the vector p[(i-1):i], which has two elements but is still considered a single object. To fix this you need to pass two separate arguments, p[i-1] and p[i]. Alternatively, modify the definition of func1 to accept a two-element vector:
func1 <- function(v)
{
x1 <- v[1]
x2 <- v[2]
result <- log(x2)-log(x1)
return(result)
}
Thank you guys,all your answers inspired me. I think I found a solution.
log_return[i-1] <- func1(p[(i-1),"Price"],p[(i),"Price"])
basically you do not need a func for those calcs in R
R's vectorization comes in handy in these cases
data <- read.csv(file="E:/Lect-1-TradingTS.csv",header=TRUE)
mode(data)
p <- data[["Price"]]
logrets <- log(p[2:length(p)]) - log(p[1:length(p)-1])
This vectorized computation will usually also heavily outperform any function you define "by hand".
Related
I have data
dat1 <- data.frame(a=1:3, b=rnorm(3))
dat2 <- data.frame(a=c(rep(1,3),rep(2,5),rep(3,4)), c=runif(12,1,50))
and a function that takes both data frames as inputs
foo <- function(dat1,dat2,par){
if(par< 25){return(dat1$b*par)}
if(par>=25){return(sum(dat2$c>par))}
}
which might work if it was embedded in a loop over different values of a.
However, I would like to find the value of par that minimizes the output of foo across all values of a. The optim() funtion should be able to do just this, but my problem is that I need to pass it two dataframes of different dimensions. I suspect some form of list could help but wouldn't know how.
from the help documentation on optim,
fn - A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.
Your function is not returning a scalar when par < 25. Since you are not changing the data.frames during optimization process, you do not have to pass in them again. Below is an example usage of optim in your case:
foo <- function(par) {
if(par < 25) {
return(sum(dat1$b*par))
} else {
return(sum(dat2$c>par))
}
}
optim(0, foo, method="Brent", lower=-1e6, upper=1e6)
I'm having troubles using several functions within the same one and calling the arguments generated. I'm using a more complicated function that can be simplified as followed:
func.essai <- function(x) {
g <- sample(seq(1,30), x)
i <- sample(x,1)
func.essai.2 <- function(y,i) {
z <- y+i
}
h <- sapply(g,func.essai.2(y,i))
}
sq <- seq(1,4)
lapply(sq, func.essai)
I'm using arguments that are generated at the beginning of func.essai (and that depend on x) as a fixed input for func.essai.2, here for i, and as a vector to go through on the sapply function, here for g. This code doesn't work as such -- it doesn't recognize y and/or i. How can I rewrite the code to do so?
I think the error you get is because of your use of sapply. This should work instead of your line containing sapply:
h <- sapply(g,func.essai.2, i)
See ?sapply, which tells you that you should provide additional arguments behind the function that you are applying.
I am trying to develop my first package in R and I am facing some issues with "myclass" generic functions that i will try to describe.
Assume a data.frame X with n <- nrow(X) rows and K <- ncol(X) columns.
My main package function (too big to put it in this post) lets say
fun1 <- function(X){
# do staff...
out <- list(index= character vector, A= A, B= B,... etc)
return(out)
class(out) <- "myclass"
}
returns as an output a list. Then I have to use the output for the generic print method in a print.myclass function. However, in my print function I want to use the data frame X used in my main function without asking the user to provide it in an argument (i.e, print(out,X)) and without having it in my output list out (visible to the user at least). Is there any way to do that? Thanks in advance!
I am trying to use the package Deriv, to compute symbolic derivatives of a function depending on one or two variables and a vector of parameters. However, i always obtain the error:
Error in FUN(X[[i]], ...) : Could not retrieve body of '[()'
I have tried:
test_fun <- function(x,y,par){x\*par[1]+y\*par[2]}
Deriv(test_fun,"x",par=c(2,2))
which yields the above error. So does
par <- c(2,2)
test_fun <- function(x,y,par){x\*par[1]+y\*par[2]}
Deriv(test_fun,"x")
Obviously
test_fun <- function(x,y,par){x\*2+y\*2}
Deriv(test_fun,"x")
works as intended, but is not what I want.
Reading the Documentation for the Deriv-package, it seems that directly passing additional arguments to the function is not supported. Is there any other way to achieve the desired result?
Updated answer (9/16):
There's two options below for passing the parameters through Deriv. Also note that Derive will retain curly braces in the original function, so either define your functions without them or call eval() afterwards.
Option 1. Define within the call to Deriv
test_fun <- function(x,y,par){x*par[1]+y*par[2]}
eval(Deriv(test_fun(par=c(2,2)),'x'))
# [1] 2
Option 2. Define the parameter values in as a function.
test_fun <- function(x,y,par){x*par[1]+y*par[2]}
tpar <- function() c(2,2)
eval(Deriv(test_fun(par=tpar()), "x"))
# [1] 2
I want to write a floor function in R, which returns a floating number to its nearest integer. So I tried the below function. It seems that it works if I assign a value to x and run the code inside the function, but it fails when I try to put everything in a function and call the function name later.
Does anyone know how to fix it?
Thanks!
> my_floor <- function(x) {
x <- x-0.5
as.integer(x)
return (x)
}
> y <- 3.1052255
> my_floor(y)
[1] 2.605225
No very sure what you are trying to do but if you simply want the input transformed to the nearest integer towards zero (i.e. floored as you your question goes), the one way to do it would be:
my_floor <- function(x) {
x <- trunc(x)
return (x)
}
This simply discards the non integer part of your input using R's trunc: which you might as well call directly i.e. trunc(y) will still give you the desired result. If you wish to use your function above "as is" then:
my_floor <- function(x) {
x <- x-0.5
x <- as.integer(x) #Store the result of this second step by reassigning x
return (x)
}