问题描述
我想做这样的事情:
df <- data.frame("v1"=c(1,2,3), "v2"=c(1,2,3), "v3"=c(1,2,3), "v4"=c(1,2,3))
a <- 2
paste0("df$v", a)
get(paste0("df$v", a))
mget(paste0("df$v", a))
输出应为控制台中打印的df$v2
内容.
The output should be df$v2
content printed in console.
问题:我这样做的主要原因是我想使用动态生成的变量名称来处理数据帧变量.我不想生成新的变量名,我只想为可用于解决它的现有变量名生成变量名.我怎样才能做到这一点?
Question: The main reason I am doing this is that I want to address the data frame variable with variable name that is generated on the fly. I do not want to generate new variable name, I only want to generate variable name to existing one that can be used for addressing it. How can I do that?
推荐答案
简短答案:使用[[
代替$
,例如df[[paste0("v",a)]]
.
Short answer: use [[
instead of $
, e.g. df[[paste0("v",a)]]
.
get()
,但是如果需要使用它,则必须分两个步骤进行操作:
get()
is not generally recommended, but if you need to use it, you'll have to do this in two steps:
get("df")[[paste0("v",a)]]
(正如@RonakShah所建议的那样,假设您知道要使用df
并使用df[[paste0("v",a)]]
会更容易理解)
(as @RonakShah suggests, it would be more idiomatic to assume you know that you're going to look in df
and use df[[paste0("v",a)]]
)
如果您坚持使用$
,则可以使用eval(parse(.))
:
If you insist on using $
, you can use eval(parse(.))
:
eval(parse(text=paste0("df$v",a)))
这篇关于如何动态生成数据帧变量名称并使用它解决现有的数据帧变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!