Ask Your Question
2

How do I delete columns that only contain NA's and/or zeros?

asked 2022-09-29 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-12-28 17:00:00 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-29 11:00:00 +0000

Seen: 18 times

Last updated: Dec 28 '22