简体   繁体   English

如何使用变量的输出来调用R中的向量

[英]How to use the output of a variable to call a vector in R

Hi can anyone help with this? 大家可以帮忙吗? I'm trying to call a vector with a variable. 我试图用一个变量调用向量。 For example? 例如?

var <- 'apple'
apple <- c(1,2,3)

but now say I have a bunch of vectors like apple and I write a function where I'm just given the var variable. 但现在说我有一堆像apple这样的向量,我写了一个函数,我只给出了var变量。 How can I access the apple vector with var ? 如何使用var访问apple vector? I tried eval(var) but that does not achieve what I want. 我尝试了eval(var)但是没有达到我想要的。 Thank you. 谢谢。

use get get

get(var)
# [1] 1, 2, 3

或使用eval(parse(text=var))

As @mnel notes, you can use get . 如@mnel所述,您可以使用get However, there is probably a better way to go about this using list s. 但是,使用list s可能有更好的方法。

If you make a list called say fruit like: 如果你做一个名为say fruitlist

apple <- 1:3
orange <- 4:6
pear <- 7:9

fruit <- list(apple=apple,orange=orange,pear=pear)
#$apple
#[1] 1 2 3
#
#$orange
#[1] 4 5 6
#
#$pear
#[1] 7 8 9

Then you can call the elements of fruit using the names you have in var like so: 然后你可以使用var的名字调用fruit元素,如下所示:

var <- "apple"

# get the whole list element named "apple"
fruit[var]
#$apple
#[1] 1 2 3

# get the contents of the list element named "apple"
fruit[[var]]
#[1] 1 2 3

If var had several different fruit names listed, it also works: 如果var列出了几种不同的水果名称,那么它也可以工作:

var <- c("apple","orange")
fruit[var]
#$apple
#[1] 1 2 3
#
#$orange
#[1] 4 5 6

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

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