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.
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
Asked: 2022-09-29 11:00:00 +0000
Seen: 18 times
Last updated: Dec 28 '22
How can the columns be transformed into a multi-level structure?
How to arrange columns in a Flutter datatable?
What is the method to obtain a count from specific columns while disregarding the rest?
What are the steps to utilize a for loop for generating and populating columns?
Is it possible that there are some missing values when combining across columns?
How can the precision be varied across different columns in pandas?