replace the last non-na entry in each row from left to right with the value from the new_col column in a dataset of many columns in r

You can use the apply function along with a custom function to replace the last non-NA entry in each row. Here's an example:

main.r
# Load necessary libraries
library(dplyr)

# Create a sample dataframe
df <- data.frame(
  col1 = c(1, 2, NA, 4),
  col2 = c(NA, 3, 5, NA),
  col3 = c(6, NA, 7, 8),
  new_col = c("a", "b", "c", "d")
)

# Define a custom function to replace the last non-NA entry
replace_last_non_na <- function(row, new_value) {
  # Find the last non-NA entry
  last_non_na_pos <- max(which(!is.na(row)))
  
  # Replace the last non-NA entry with the new value
  row[last_non_na_pos] <- new_value
  
  return(row)
}

# Apply the custom function to each row
df <- df %>%
  rowwise() %>%
  mutate(
    row_values = list(replace_last_non_na(unlist(select(., -new_col)), new_col))
  ) %>%
  unnest_wider(row_values) %>%
  select(-new_col)

# Print the resulting dataframe
print(df)
761 chars
34 lines

This code defines a custom function replace_last_non_na that takes a row and a new value as input, finds the last non-NA entry in the row, and replaces it with the new value. The apply function is then used to apply this custom function to each row of the dataframe, replacing the last non-NA entry with the value from the new_col column.

Note that this code uses the dplyr library for data manipulation and assumes that the dataframe has a column named new_col containing the values to replace the last non-NA entry with.

related categories

gistlibby LogSnag