Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To substitute a value in a data.frame while using a function that can be applied, you can use the apply function. Here is an example:

Suppose you have a data.frame df with columns col1 and col2, and you want to substitute all occurrences of the value 0 in col1 with the value 1:

df <- data.frame(col1 = c(0, 1, 2), col2 = c(3, 4, 5))

You can create a function that takes a vector and substitutes all 0's with 1's:

substitute_zero <- function(x) {
  x[x == 0] <- 1
  return(x)
}

Then, you can apply this function to col1 using apply:

df[, "col1"] <- apply(df[, "col1", drop = FALSE], 1, substitute_zero)

This will replace all 0's in col1 with 1's. Note that we use drop = FALSE to preserve the data.frame structure when subsetting df.