简体   繁体   English

在R中命名的元素操作

[英]named Element-wise operations in 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) 我是R的初学者并提前道歉提出了一个基本问题,但我无法在谷歌的任何地方找到答案(也许是因为这个问题非常基本,我甚至不知道如何正确搜索它......: d)

So if I do the following in R: 所以,如果我在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? 为什么名称“First”出现在输出中以及如何摆脱它?

From help("Extract") , this is because help("Extract") ,这是因为

Subsetting (except by an empty index) will drop all attributes except names , dim and dimnames . 子集(除了空索引)将删除除namesdimdimnames之外的所有属性。

and

The usual form of indexing is [ . 通常的索引形式是[ [[ can be used to select a single element dropping names , whereas [ keeps them, eg, in c(abc = 123)[1] . [[可用于选择单个元素删除names ,而[保留它们,例如,在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. 我们必须深入研究C源以获得进一步的解释。 If we switch the order, we still get the first name on the result. 如果我们切换订单,我们仍会得到结果的第一个名字。

v["Last"] / v["First"]
# Last 
#  0.5 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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