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
You can simple use
a <- data_frame(keep=c("hello", "world"),drop = c("nice", "work"))
select(a, -starts_with('drop'))
# Source: local data frame [2 x 1]
#
# keep
# (chr)
# 1 hello
# 2 world
you have to search for some previously written solutions too. Please read the document here Select/rename variables by name.DPLYR
I hope that does the job for you :)
@Psidom thanx for updating your answer.. but I will request upvoters for vote for me too as I recently became an active user and still am to get basic privileges on stackoverflow.
We can use select
with setdiff
a %>%
select_(setdiff(names(.), name))
# A tibble: 2 × 1
# keep
# <chr>
#1 hello
#2 world
A few more possibilities:
name <- "drop"
a %>% `[<-`(name, value=NULL)
a %>% magrittr::inset(name,value=NULL)
a %>% purrr::modify_at(name,~NULL)
I could only get these solutions to work by first ungrouping the data using ungroup
:
df <- df %>% ungroup %>% select(-hello)
Notice no quotation marks on the column name you want to drop (hello). Also, to remove multiple columns, just place a ,
after hello and add the second column.