I am a beginner in R and apologize in advance for asking a basic question, but I couldn't find answer anywhere on Google (maybe because the question is so basic that I didn't even know how to correctly search for it.. :D)
So if I do the following in R:
v = c(50, 25)
names(v) = c("First", "Last")
v["First"]/v["Last"]
I get the output as:
First
2
Why is it that the name, "First" appears in the output and how to get rid of it?
From help("Extract")
, this is because
Subsetting (except by an empty index) will drop all attributes except
names
,dim
anddimnames
.
and
The usual form of indexing is
[
.[[
can be used to select a single element droppingnames
, whereas[
keeps them, e.g., inc(abc = 123)[1]
.
Since we are selecting single elements, you can switch to double-bracket indexing [[
and names will be dropped.
v[["First"]] / v[["Last"]]
# [1] 2
As for which name is preserved when using single bracket indexing, it looks like it's always the first (at least with the /
operator). We'd have to go digging into the C source for further explanation. If we switch the order, we still get the first name on the result.
v["Last"] / v["First"]
# Last
# 0.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With