Home > OS >  Remove column if it contains certain heading
Remove column if it contains certain heading

Time:04-14

When I read a file into my model, sometimes it contains a column named 'X' that just has the number of rows in the file. I can easily remove it but I would like to not have to check each time. How can I write an if statement that removes a column if its named X? I already know what to put in the if statement

    df <- subset(df, select=-X)
X Values
1 100
2 150

CodePudding user response:

This method will delete it if present and not throw an error if not present:

df[["X"]] = NULL

Or, as you say, you can write an if statement:

if("X" %in% colnames(df)) {
  df <- subset(df, select = -X)
}
  •  Tags:  
  • r
  • Related