2

I want to apply a user defined function to a specific column for every row in a dataframe in R and save the result back into the column.

1 Answer 1

6

After nearly 3 hours of reading Stack Overflow answers about slightly different use cases and playing around with apply, lapply, sapply etc. here's the code that allows you to do this:

your_function <- function(x) {
    if(x == 3) {
        x = 333
    } else {
        x = 1
    }
}

df$colname <- sapply(df$colname, your_function)
Sign up to request clarification or add additional context in comments.

4 Comments

Did you know the answer before asking it?
Why question and answer both are posted in the same time? If you know the answer than what is the reason for posting the question?
Well, seeing as I couldn't find the answer to my question elsewhere. I figured perhaps posting what I found might help someone else with the same question. There's actually a checkbox you can check to answer your own question.
Yeah, it's explicitly encouraged: stackoverflow.com/help/self-answer Thanks for sharing @stroz - it helped me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.