简体   繁体   中英

Subsetting a Vector in R with a numeric

I'm trying to better understand indexing/subsetting behaviour.

Consider the numeric vector x :

x <- c(1.0, 2.0)

I can get at its values:

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

But I'm confused by these returns:

x[1.1]
#> [1] 1
x[2.7]
#> [1] 2
x[3.1]
#> [1] NA

Moreover it seems this doesn't work like I would expect:

x[2.6] <- 3.0 
x
#> [1] 1 3

Can someone help me understand why this is?

Okay so the core issue was the I didn't know about:

?`[`

which as @BondedDust points out tells you:

indices specifying elements to extract or replace. Indices are numeric or character vectors or empty (missing) or NULL. Numeric values are coerced to integer as by as.integer (and hence truncated towards zero). Character vectors will be matched to the names of the object (or for matrices/arrays, the dimnames): see 'Character indices' below for further details.

So it was just that the behaviour was defined this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM