R:在字符串中调用对象

时间:2016-02-17 06:19:29

标签: r

> foo <- as.character(c(0, 2))
> foo
[1] "0" "2"
> foo[1]
[1] "0"
> foo[2]
[1] "2"

> as.character("0-2")
[1] "0-2"  #this is the output I want from the command below:

> as.character("foo[1]-foo[2]")
[1] "foo[1]-foo[2]"  # ... was hoping to get "0-2"

我尝试了eval(parse())的一些变体,但同样的问题。我也试过这些简单的例子:

> as.character("as.name(foo[1])")
[1] "as.name(foo[1])"
> as.character(as.name("foo[1]"))
[1] "foo[1]"

是否有机会像as.character("foo[1]-foo[2]")这样简单地展示"0-2"

更新

类似的例子(字符串长得多):

> lol <- as.character(seq(0, 20, 2))
> lol
 [1] "0"  "2"  "4"  "6"  "8"  "10" "12" "14" "16" "18" "20"

 > c(as.character("0-2"), as.character("2-4"), as.character("4-6"), as.character("6-8"), as.character("8-10"), as.character("10-12"), as.character("12-14"),as.character("14-16"),as.character("16-18"),as.character("18-20"))
 [1] "0-2"   "2-4"   "4-6"   "6-8"   "8-10"  "10-12" "12-14" "14-16" "16-18" "18-20"

我希望能够在我的字符串中实际调用对象lol

1 个答案:

答案 0 :(得分:4)

我们可以将pastecollapse参数

一起使用
paste(foo, collapse='-')
#[1] "0-2"

如果我们需要paste个相邻元素,请删除'lol'的第一个和最后一个元素,然后将pastesep参数一起删除。

paste(lol[-length(lol)], lol[-1], sep='-')
#[1] "0-2"   "2-4"   "4-6"   "6-8"   "8-10"  "10-12" "12-14" "14-16" "16-18"
#[10] "18-20"