如何使用dplyr SE与“无效”名称(即包含空格)? [英] How to use dplyr SE with "invalid" names (ie containing spaces)?
问题描述
我不知道如何使用无效变量名称的SE dplyr函数,例如选择一个带有空格的变量。
I can't figure out how to use SE dplyr function with invalid variable names, for example selecting a variable with a space in it.
示例: p>
Example:
df <- dplyr::data_frame(`a b` = 1)
myvar <- "a b"
如果我想选择 ab
变量,我可以使用 dplyr :: select(df,`ab`)
,但是如何使用 select _
If I want to select a b
variable, I can do it with dplyr::select(df, `a b`)
, but how do I do that with select_
?
我想我只需要找到一个函数,将一个字符串wrap为反引号,这样我可以调用 dplyr :: select_(df ,backtick(myvar))
I suppose I just need to find a function that "wraps" a string in backticks, so that I can call dplyr::select_(df, backtick(myvar))
推荐答案
正如MyFlick在评论中所说,这个行为一般应该是避免,但是如果你想让它工作,你可以使自己的backtick包装器
As MyFlick said in the comments, this behaviour should generally be avoided, but if you want to make it work you can make your own backtick wrapper
backtick <- function(x) paste0("`", x, "`")
dplyr::select_(df, backtick(myvar))
编辑:哈德利回覆了关于我的推文并展示给我一个简单的使用 as.name
将适用于此而不是使用反引号:
Hadley replied to my tweets about this and showed me that simply using as.name
will work for this instead of using backticks:
df <- dplyr::data_frame(`a b` = 1)
myvar <- "a b"
dplyr::select_(df, as.name(myvar))
这篇关于如何使用dplyr SE与“无效”名称(即包含空格)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!