Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

named Element-wise operations in R

Tags:

r

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?

like image 673
TotalGadha Avatar asked Feb 17 '17 04:02

TotalGadha


1 Answers

From help("Extract"), this is because

Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.

and

The usual form of indexing is [. [[ can be used to select a single element dropping names, whereas [ keeps them, e.g., in c(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 
like image 116
Rich Scriven Avatar answered Oct 22 '22 08:10

Rich Scriven