如何通过使用dplyr传递变量名来删除列? [英] how to drop columns by passing variable name with dplyr?

查看:112
本文介绍了如何通过使用dplyr传递变量名来删除列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个df,如下所示:

I have a df as follows:

a <- data_frame(keep=c("hello", "world"),drop = c("nice", "work"))
a
Source: local data frame [2 x 2]
 keep  drop
(chr) (chr)

1 hello nice
2世界工作

1 hello nice 2 world work

我可以使用 a%>%select(-drop)删除列没有问题。但是,如果我想传递一个变量来呈现 drop 列,那么它返回错误。

I can use a %>% select(-drop) to drop the column without problem. however, if I want to pass a variable to present drop column, then it returns error.

name <- "drop"
a  %>% select(-(name))
Error in -(name) : invalid argument to unary operator


推荐答案

您可以使用 one_of 来查找列位置,然后使用 - 删除它,选择(-one_of(name)),如果您检查?选择,则使用情况记录在拖放变量 示例中的部分:

You can use one_of to find the column positions and then use - to drop it, select(-one_of(name)), if you check ?select, the usage is documented in the Drop variable section in the Examples:

name <- "drop"
a %>% select(-one_of(name))

# A tibble: 2 × 1
#   keep
#  <chr>
#1 hello
#2 world






或者使用 select _ ,您需要使用列名粘贴 - ,以将其放下并传递粘贴列名称到 .dots 参数,如果有多个列要删除:


Or with select_, you need to paste - with the column names to drop them and pass the pasted column names to the .dots parameter if there are more than one column to be dropped:

name <- "drop"
a %>% select_(.dots = paste("-", name))

# A tibble: 2 × 1
#   keep
#  <chr>
#1 hello
#2 world

这篇关于如何通过使用dplyr传递变量名来删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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