How to remove variables with no name (NA in variable name)

I am not able to deselect variables that have no names at all. There are few columns or variables which have no values in my data and no name for the variable itself. How can we remove these columns?

Thanks for your help!

Can you give a short example in code form?

The brute force way is to subset them out by column position. Assuming even number columns need removing

my_df[,c(2,4,6)] -> my_df

Thanks @HanOostdijk! I tried creating a Reprex, but it doesn't seem to work right with this kind of data. Below code shows that there are 2 empty columns which I would like remove. But basically, there are few blank columns inserted in between.

df <- data.frame(
  check.names = FALSE,
                                                          `Var 1` = c(3834921.939,3855495.379,4162283.974,3956484.826,
                                   NA),
         ...2 = c(NA, NA, NA, NA),
      `Var 2` = c(70, 69, 65, 64),
         ...4 = c(NA, NA, NA, NA),
                       `Var 3` = c(60698.1057142857,65483.6194736842,66612.7236363636,
                                   62579.2695)
                 )

Below is a screenshot of this dataframe example where 2 empty columns need to be removed.
image

Thank you!

Thanks @technocrat! Yes, that is possible. But if I get into this kind of situation with large data set, then this approach will not be ideal. I hope there is a way to handle this particular problem.

Are all of the unwanted colums full of NA? If so, you can subset against is.na() or sumCols. If not, there's vec_as_names {vctrs}

Thanks @technocrat! colSums worked

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.