head with non integer n returns confusing output

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

head with non integer n returns confusing output

Ant F
Dear all,

`head()` returns a problematic output when a character is fed to its `n`
parameter.

doubles and logicals are converted to integer as if `as.integer` was used,
which I think is intuitive enough :

```
head(1:10, 4.1)  # [1] 1 2 3 4
head(1:10, 4.9)  # [1] 1 2 3 4
head(1:10, TRUE)  # 1
head(1:10, FALSE) # integer(0)
```

But characters have a stranger behavior :

```
head(1:10, "0") # integer(0)
head(1:10, "0.1") # integer(0)
head(1:10, "1") # [1] 1
head(1:10, "1.2") # [1] 1
head(1:10, "2") # [1] [1]  1  2  3  4  5  6  7  8  9 10
head(1:10, "-1") # Error in length(x) + n : non-numeric argument to binary
operator
head(1:10, "-0") # Error in length(x) + n : non-numeric argument to binary
operator
head(1:10, "foo") # [1]  1  2  3  4  5  6  7  8  9 10
```

When forgetting to convert user input to numeric this can lead to an
unexpected and inconsistent result.

I would suggest either using `as.integer` consistently on the input, or
having a consistent error for all character input.

`n = NA` also a returns a somewhat misleading error as it demands a logical
input while the top level function requires an integer input.

```
head(1:10, NA)  # same output for head(1:10, NA_integer_)
# Error in if (n < 0L) max(length(x) + n, 0L) else min(n, length(x)) :
#   missing value where TRUE/FALSE needed
```

Kind regards,

Antoine

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Reply | Threaded
Open this post in threaded view
|

Re: head with non integer n returns confusing output

Abby Spurdle
> `head()` returns a problematic output when a character is fed to its `n`
> parameter.
> this can lead to an unexpected and inconsistent result.
> I would suggest either using `as.integer` consistently on the input, or
> having a consistent error for all character input.

I use the head() and tail() functions, a lot.
I agree that the argument checking and argument handling is not as good as
it could be.

In march I posted the following thread:
https://stat.ethz.ch/pipermail/r-devel/2019-March/077512.html
https://stat.ethz.ch/pipermail/r-devel/2019-March/077527.html

Perhaps, head (1:10, "foo"), should return a clear error message...
Then it's up to the user to convert strings to integers, if that's want he
or she wants to do.

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel