Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming you are working with a dataframe in R, you can try the following code:

# Generate a sample dataframe with some columns containing NA's and/or zeros
df <- data.frame(
  A = c(1, 2, 3),
  B = c(0, 0, 0),
  C = c(NA, NA, NA),
  D = c(4, 5, 6),
  E = c(7, 8, 9)
)

# Find columns that contain only NA's and/or zeros
cols_to_delete <- sapply(df, function(x) all(is.na(x) | x == 0))

# Remove the columns from the dataframe
df <- df[, !cols_to_delete]

This code uses the sapply function to check each column of the dataframe. The function all(is.na(x) | x == 0) checks if all values in the column are either NA or zero. The resulting vector tells us which columns should be deleted. Finally, we subset the dataframe using the [, !cols_to_delete] notation to remove the desired columns.