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

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

问题描述

我有一个 df 如下:

a <- data_frame(keep=c("hello", "world"),drop = c("nice", "work"))一个来源:本地数据框 [2 x 2]保持下降(chr) (chr)1 你好2 世界工作

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

name <- drop";%>% select(-(name))

<块引用>

-(name) 中的错误:一元运算符的参数无效

解决方案

可以使用one_of找到列位置,然后使用-删除,select(-one_of(name)),如果你勾选?select,用法记录在示例中的Drop 变量部分:

name <- "drop"%>% select(-one_of(name))# 小费:2 × 1#   保持# <chr>#1 你好#2 世界

<小时>

或使用select_,您需要将- 与列名粘贴以删除它们并将粘贴的列名传递给.dots如果要删除的列不止一列,则参数:

name <- "drop"a %>% select_(.dots = paste("-", name))# 小费:2 × 1#   保持# <chr>#1 你好#2 世界

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 world  work

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

解决方案

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


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天全站免登陆