R dplyr过滤器列,列名以数字开头 [英] R dplyr filter column with column name that starts with number

查看:62
本文介绍了R dplyr过滤器列,列名以数字开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎重复的
如何引用那些以data.table中的数字开头
上面的帖子介绍了 data.table .这个问题是相似的,但在技术上取决于包装,但是解决方案是相同的.

a near-duplicate
How to reference column names that start with a number, in data.table
The post above regards data.table. The problem is similar but technically package-dependent, but the solution is the same.

原始帖子的开始

我无法弄清楚如何使用 dplyr :: filter

I'm unable to figure out how to filter the following column with dplyr::filter

set.seed(1)
library(dplyr)
df <- as.data.frame(matrix(sample(c(TRUE, FALSE), 10, replace=TRUE), ncol=1)) %>%
        setNames(c(paste0("1", letters[1])))
      # 1a
# 1   TRUE
# 2   TRUE
# 3  FALSE
# 4  FALSE
# 5   TRUE
# 6  FALSE
# 7  FALSE
# 8  FALSE
# 9  FALSE
# 10  TRUE

df[df$"1a"==TRUE,]
# [1] TRUE TRUE TRUE TRUE

df %>% dplyr::filter("1a"==TRUE)
# [1] 1a
# <0 rows> (or 0-length row.names)

推荐答案

您可以使用反引号来引用具有非标准名称的变量.无论它们是否是数据框的列,这都行得通.

You can use backticks to refer to variables with non-standard names. This works whether they are columns of a data frame or not.

在这种情况下

df %>% dplyr::filter(`1a`)  # note that == TRUE is never needed

或者一般来说,

`2b` = 1:5
mean(`2b`)
# [1] 3

当然,您不应该对此养成不良习惯-尽可能使用标准名称.

Of course you shouldn't make a bad habit of this - use standard names whenever possible.

如评论中所述,?Quotes 文档很有帮助.它指出(在名称和标识符部分中):

As mentioned in comments, the ?Quotes documentation is helpful. It states (in the Names and Identifiers section):

几乎总是可以使用其他名称,只要将它们加引号即可.首选的引号是反引号(`),通常使用 deparse ,但是在许多情况下,可以使用单引号或双引号(因为字符常量通常会转换为名称).可能需要反引号的一个地方是在公式中定界变量名称:请参见公式.

Almost always, other names can be used provided they are quoted. The preferred quote is the backtick (`), and deparse will normally use it, but under many circumstances single or double quotes can be used (as a character constant will often be converted to a name). One place where backticks may be essential is to delimit variable names in formulae: see formula.

这篇关于R dplyr过滤器列,列名以数字开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆