create a new column from a dataframe that returns the minimum number in one specific column and ignores na in r in r

You can create a new column in a dataframe that contains the minimum number from a specific column while ignoring NA values in R using the mutate function from the dplyr package. Here's an example to achieve this:

library(dplyr)

# Create an example dataframe
df <- data.frame(x = c(3, 5, NA, 2, 8, 4),
                 y = c(7, 2, 6, NA, 3, 1))

# Add a new column with the minimum value of column 'x' ignoring NA values
df <- df %>%
  mutate(min_x = na.omit(x)) %>%
  mutate(min_x = ifelse(length(min_x) == 0, NA, min(min_x, na.rm = TRUE)))

print(df)
340 chars
13 lines

In this code snippet, we first load the dplyr package. Then, we create an example dataframe df. We use the mutate function twice to first remove NA values from column 'x' using na.omit and then calculate the minimum value of the remaining elements using min. The na.rm = TRUE argument in min ensures that NA values are ignored during calculation.

After running this code, you will have a new column min_x in the dataframe df that contains the minimum value of the 'x' column while ignoring NA values.

related categories

gistlibby LogSnag