Home > Net >  Selecting unnamed columns in R
Selecting unnamed columns in R

Time:11-02

After reading in some data, I somehow have several columns which are all named "". I would like to remove these columns from my dataframe. For example,

x <- tribble(
~ a, ~ b, ~"", ~"",
  1, 2, NA, NA,
  3, 4, NA, NA
)
select(x, -"")

However, this throws an Error: names can't be empty. I also tried:

select(x, -where(~ .x == ""))

But it says where() must be used with functions that return TRUE or FALSE. I really don't want to select based on position (ie 3, 4) but I'm having trouble finding a solution.

CodePudding user response:

How about subsetting by the number of characters in the column name?

x <- tribble(
  ~ a, ~ b, ~"", ~"",
  1, 2, NA, NA,
  3, 4, NA, NA
)
x[,nchar(names(x))>0]
# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1     1     2
2     3     4

CodePudding user response:

An option is also

library(dplyr)
x %>% 
   select(-matches('^$'))
# A tibble: 2 × 2
      a     b
  <dbl> <dbl>
1     1     2
2     3     4

CodePudding user response:

Yet another solution:

select_if(x, ~ all(. != ""))

Or yet:

select_if(x, ~ !is.null(.))
  • Related