简体   繁体   English

引导程序或列表的呼叫名称

[英]Call names of a vector or list

I have a vector named "vec". 我有一个名为“ vec”的向量。 I label the elements from "a" to "m" 我将元素从“ a”标记为“ m”

vec <- c(1,1,1,2,2,2,2,2,2,4,4,4,4)
names(vec) <- c("a","b","c","d","e","f","g","h","i","j","k","l","m")

Then I split the vec according to the sequences. 然后,我根据顺序拆分了vec。

split_vec <- split(vec, vec)

Now when I type Spec_vec$"1" I get the first list. 现在,当我键入Spec_vec$"1"我得到第一个列表。

Instead of typing the specific name as "1". 而不是将特定名称键入为“ 1”。 I want to get the values such as 我想获取诸如

spec_vec$vec[1] But the above function doesn't work. spec_vec$vec[1]但是上面的功能不起作用。 Is there a way to get that? 有办法吗?

You can do 你可以做

split_vec[[as.character(vec[1])]]
# a b c 
# 1 1 1 

Notice that you need as.character , since just the number value from vec[i] would give incorrect results for calls like split_vec[[vec[10]]] where you would expect the third element. 注意,您需要as.character ,因为对于像split_vec[[vec[10]]]这样的调用,如果您希望第三个元素as.character ,仅来自vec[i]的数字值将给出错误的结果。

split_vec[[vec[10]]]
# Error in split_vec[[vec[10]]] : subscript out of bounds

split_vec[[as.character(vec[10])]]
# j k l m 
# 4 4 4 4 

But in general, it's best to avoid such names that begin with numerics because, obviously, it's quite awkward and can cause trouble. 但是总的来说,最好避免使用以数字开头的名称,因为很显然这很尴尬并可能引起麻烦。

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

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