Ask Your Question
2

How can I substitute a value in a data.frame while using a function that can be applied?

asked 2023-05-02 10:12:08 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-02 10:34:01 +0000

devzero gravatar image

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.

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: 2023-05-02 10:12:08 +0000

Seen: 8 times

Last updated: May 02 '23