R argument is missing, with no default

Viewed 34910

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


3 Answers

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