. Advertisement .
..3..
. Advertisement .
..4..
Here is the program I run:
Transaction <- function(PnL, Day)
results <- list(a = PnL, b = Day)
return(results)
Day <- Transaction(PnL, Day)["b"]
moving_avg <- function(StockData, MA, CurrentDay){
#MA = Days long the MA is
#CurrentDay = What day we are currently on
MAValue <- NULL
total <- 0
start <- CurrentDay - MA
for(i in 1:length(MA)) {
total <- total + StockData[[start, 4]]
start <- start + 1
}
MAValue <- total/MA
return(MAValue)
}
After I run, it returns an error:
Error in CurrentDay - MA : non-numeric argument to binary operator
Does anyone have any suggestions for the problem below: error in fun(left, right) : non-numeric argument to binary operator in the r – How to correct it?
The cause:
This error occurs because you are trying to perform
-
as the ‘binary operator’, butCurrentDay
orMA
is non-numeric, even both of them are non-numeric.Solution:
This error will be solved if you run the following program before your code:
Your question is not about your function, but rather the error message. I will address it.
-
refers to the ‘binary operator’ that your error is referencing.CurrentDay
andMA
are both non-numeric.Binary operations are calculations that take two values (operands), and produce another value ( refer to Wikipedia for more).
+
is an example of such an operator. “1 + 1” takes 2 operands (1 & 1) and returns another (2). The produced value doesn’t necessarily differ from the operands, e.g. 1 + 0 = 1.R knows only how to apply
+
and other binary operators such as-
to numeric arguments.If you see this error message, it is likely that you (or the function that you’re calling) are trying to perform a binary operations with something that’s not a number.
EDIT:
Your mistake is in using
[
rather than[[
. SubsettingDay
with[
will result in a list and not a numeric vector, sinceDay
can be used as a list.[[
returns however an object of class of the item in the list.Transaction
returns two vectors, as you have defined it.Day
, as you can see, returns a list that contains one vector.Day2
is a vector.