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
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)
4 Comments
umutto
Did you know the answer before asking it?
Saurabh Chauhan
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?
stroz
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.
Hobo
Yeah, it's explicitly encouraged: stackoverflow.com/help/self-answer Thanks for sharing @stroz - it helped me