将值序列转换为替换表达式序列

3

我想要制作

list(quote(10^2), quote(10^3), quote(10^4),
     quote(10^5), quote(10^6), quote(10^7))

来自

seq(2,7)

有没有比那种方法更好的方式?
mapply(function(n) substitute(10^x, list(x=as.double(n))), seq(2,7))

我已经尝试了以下方法:

> substitute(10^x, list(x=seq(2,7)))
10^2:7

> mapply(substitute, 10^x, x=seq(2,7))
Error in mapply(substitute, 10^x, x = seq(2, 7)) : object 'x' not found

> mapply(function(n) substitute(10^n), seq(2,7))
list(10^dots[[1L]][[6L]], 10^dots[[1L]][[6L]], 10^dots[[1L]][[6L]], 
     10^dots[[1L]][[6L]], 10^dots[[1L]][[6L]], 10^dots[[1L]][[6L]])
2个回答

7

试试使用bquote

lapply(as.numeric(2:7), function(x) bquote(10^.(x)))

这很好地运作了,结果我甚至不需要使用 as.numeric - zwol
你能解释一下在这种情况下,使用bquote是否比substitute更有优势吗? - A5C1D2H2I1M1N2O1R2T1
我认为这只是你喜欢哪种语法的问题。bquote使用substitute - G. Grothendieck

2

您应该能够做到以下几点:

lapply(2:7, function(x) {
  substitute(10^x, list(x = x))
})

示例:

test <- lapply(2:7, function(x) {
  substitute(10^x, list(x = x))
})
str(test)
# List of 6
#  $ : language 10^2L
#  $ : language 10^3L
#  $ : language 10^4L
#  $ : language 10^5L
#  $ : language 10^6L
#  $ : language 10^7L

orig <- list(quote(10^2), quote(10^3), quote(10^4),
             quote(10^5), quote(10^6), quote(10^7))
str(orig)
# List of 6
#  $ : language 10^2
#  $ : language 10^3
#  $ : language 10^4
#  $ : language 10^5
#  $ : language 10^6
#  $ : language 10^7

唯一的区别在于我的版本将2:7的值视为整数(因此是“L”)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接