【发布时间】:2015-09-26 21:08:07
【问题描述】:
我正在尝试更好地理解索引/子集化行为。
考虑数字向量x:
x <- c(1.0, 2.0)
我可以得到它的价值:
x[1L] # the first element of a 1-indexed vector
#> [1] 1
x[2L] # the second element of a 1-indexed vector
#> [1] 2
x[3L] # the third element, which is not defined/ does not exists, so returns `NA`; ok.
#> [1] NA
但我对这些回报感到困惑:
x[1.1]
#> [1] 1
x[2.7]
#> [1] 2
x[3.1]
#> [1] NA
此外,这似乎不像我预期的那样工作:
x[2.6] <- 3.0
x
#> [1] 1 3
谁能帮我理解这是为什么?
【问题讨论】:
-
这个索引被做成一个整数。所以索引变为
as.integer(2.7),即2 -
有趣。你知道为什么决定使用 floor() 索引吗?如果输入了非整数数字索引,返回错误似乎是健康的。
-
我真的不知道他们为什么这样写,我也不知道
as.integer()是否被实现,因为[是一个原始函数,所以它直接进入C代码.我所知道的是它就是这样工作的,它就是这样。 ;) -
很公平,如果您碰巧知道的话,我只是想了解有关此非正统功能的更多信息。
-
如帮助页面所说:
Numeric values are coerced to integer as by as.integer (and hence truncated towards zero).
标签: r