I am having a little problem with R and I am not sure why. It is telling me that this line: if(temp > data[[k]][[k2]]) {
is of argument length 0. Here is the
The simplest solution to the problem is to change your for loop statement :
Instead of using
for (i in **0**:n))
Use
for (i in **1**:n))
I spent an entire day bashing my head against this, the solution turned out to be simple..
R isn't zero-index.
Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.
Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.
You can use isTRUE
for such cases. isTRUE
is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }
If you use shiny there you could use isTruthy
which covers the following cases:
FALSE
NULL
""
An empty atomic vector
An atomic vector that contains only missing values
A logical vector that contains all FALSE or missing values
An object of class "try-error"
A value that represents an unclicked actionButton()
The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).
You can further verify my point by finding the class of your output-
>class(output)
"integer"
"argument is of length zero" is a very specific problem that comes from one of my least-liked elements of R. Let me demonstrate the problem:
> FALSE == "turnip"
[1] FALSE
> TRUE == "turnip"
[1] FALSE
> NA == "turnip"
[1] NA
> NULL == "turnip"
logical(0)
As you can see, comparisons to a NULL not only don't produce a boolean value, they don't produce a value at all - and control flows tend to expect that a check will produce some kind of output. When they produce a zero-length output... "argument is of length zero".
(I have a very long rant about why this infuriates me so much. It can wait.)
So, my question; what's the output of sum(is.null(data[[k]]))
? If it's not 0, you have NULL values embedded in your dataset and will need to either remove the relevant rows, or change the check to
if(!is.null(data[[k]][[k2]]) & temp > data[[k]][[k2]]){
#do stuff
}
Hopefully that helps; it's hard to tell without the entire dataset. If it doesn't help, and the problem is not a NULL value getting in somewhere, I'm afraid I have no idea.
The same error message results not only for null
but also for e.g. factor(0)
. In this case, the query must be if(length(element) > 0 & otherCondition)
or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition)
.