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)
}
Related
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 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".
If my function has input (x,y,z) in R, I want to write a line of code which ensures data for x is of the right form.
i.e. x is just a real number rather than anything else such as a vector or a list. I assume the code would go something like
if ( ... ){stop("x must be a real number")}
I would like to know what goes inside of the bracket instead of ... ?
The reason is that if I write in a vector, the programme just take the first component of the vector as the input. R would give a warning about this, but I would like the programme to be stopped immediately.
If you want to "stop" if your argument is of length 1, and a real number
You could use stopifnot
foo <- function(x, y, z) {
stopifnot(length(x)==1L & is.numeric(x))
}
or perhaps
foo <- function(x, y, z){
if(!(length(x)==1L & is.numeric(x))) { stop("x must be a real number")}
}
stop allows you to specify the error message whereas stopifnot will return the condition that was tested. (Both have advantages)
The benefit of stopifnot is that it can tell you exactly which of multiple conditions failed.for example (noting that I am now feeding multiple expressions)
foo <- function(x, y, z) {
stopifnot(length(x)==1L , is.numeric(x))
}
foo('a')
# Error: is.numeric(x) is not TRUE
foo(c(1,2))
# Error: length(x) == 1L is not TRUE
Easier to ask by example. If I have a function
fn <- function(x) {
...
return(c(a,b,c))
}
and I wish to maximize (or minimize) with respect to a, but also get the values of b and c at the optimal value.
Of course I can use fn2 <- function(x) fn(x)[1] to determine the optimal value, then call the function again, but I wonder if there is a smarter way of doing this.
optim needs the return value to be a scalar. The documentation says so
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.
You could write the values of interest to a global variable inside your function though. This isn't necessarily best practice but it could work.
f <- function(x){
.vals <<- c(x, x+1)
x^2
}
optim(1, f)
then after we can look at what is stored in .vals
> .vals
[1] 9.765625e-05 1.000098e+00
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
General suggestions for debugging R?
When debugging, I would often like to know the value of a variable used in a function that has completed executing. How can that be achieved?
Example:
I have function:
MyFunction <- function() {
x <- rnorm(10) # assign 10 random normal numbers to x
return(mean(x))
}
I would like to know the values stored in x which are not available to me after the function is done executing and the function's environment is cleaned up.
You mentioned debugging, so I assume the values are not needed later in the script, you just want to check what is happening. In that case, what I always do is use browser:
MyFunction <- function() {
browser()
x <- rnorm(10) # assign 10 random normal numbers to x
return(mean(x))
}
This drops you into an interactive console inside the scope of the function, allowing you to inspect what is happening inside.
For general information about debugging in R I suggest this SO post.
MyFunction <- function() {
x <- rnorm(10) # assign 10 random normal numbers to x
return(list(x,mean(x)))
}
This will return a list where the first element is x and the second is its mean
You have many options here. The easiest is to use the <<- operator when you assign to x. It's also the most likely to get you into trouble.
> test <- function() x <- runif(1)
> x <- NA
> test()
> x
[1] NA
> test <- function() x <<- runif(1)
> test()
> x
[1] 0.7753325
Edit
#PaulHeimstra points out that you'd like this for debugging. Here's a pointer to some general tricks:
General suggestions for debugging in R
I'd recommend either setting options(error=recover) or using trace() in combination with browser().
There are already some good solutions, I'd like to add one possibility. I emphasize on the fact that you want to know the value of a variable used in a function that has completed executing. So there is maybe no need to assign those values, and you don't want (a priori) to stop execution. The solution is to simply use print. So it is not used by default but only when you want to debug, the option to print or not can be passed as a function argument:
MyFunction <- function(x, y, verbose = FALSE) {
a <- x * y
if (verbose) print(a)
b <- x - y
if (verbose) print(b)
return(a * b)
}
In general, you would run your function like this: MyFunction(10, 4) but when you want to see those intermediate results, do MyFunction(10, 4, verbose = TRUE).