I'm new to R (and coding in general) so apologies if this is a stupid question, I suspect it's an easy fix and I'm just not understanding how to make a function correctly but we'll see.
I want to add a new column to a data frame, that contains a string that is dependent on the value contained in an existing column. For example with iris data, if a row contains the value of "0.2" in the Petal.Width column, I'd like to paste a string like "Response String 1" in a new column. And if the value in Petal.Width = 0.4, then to paste "Response String 2" in the same column.
I've tried to figure it out with help from here and here but haven't been able to make it work.
So far I have something like this:
MyFunction <- function(petalWidth){
if (petalWidth == 0.2){
iris$NewColumn <- paste("Response String 1")
}
}
apply(iris, 1, MyFunction(iris$Petal.Width))
Comes up with this error:
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'Response String 1' of mode 'function' was not found
In addition: Warning message:
In if (petalWidth == 0.2) { :
the condition has length > 1 and only the first element will be used
I've tried a few other ways, including looking into a for
statement. I'm not really sure how to construct this function to work properly. Any ideas would be greatly appreciated and I hope I've provided enough to make this reproducible. Thanks!