Reputation: 101
Edit: The suggested code worked, so in total:
MyData$Numbers_2=with(MyData, ifelse(Numbers %in% MyVector,
paste0("L_N", Numbers),
paste0("L_", Numbers)))
This adds a column with the new (character) values.
I'd like to add a specific string of characters to every value in a column of a dataframe, based on the condition that the value is found in a vector.
#Create Dataframe
MyData=data.frame(Numbers=c(85,84,7,9,82,5,81,80,10))
MyVector=c("80","81","82","83","84","85")
# for Loop with if else condition
for (Nr in MyVector) {MyData$Numbers_2=as.character(MyData$Numbers)
if(is.element(Nr,MyData$Numbers_2)) {MyData$Numbers_2= paste("L_N",MyData$Numbers_2, sep = "")}
else {MyData$Numbers_2= paste("L_",MyData$Numbers_2, sep = "")}
}
Basically, I'd like to have a result like this:
L_N85, L_N84, L_7, L_9 etc.
But what I get is: L_N85, L_N84, L_N7, L_N9.
It adds L_N to every value in the column, and not only to specific ones. How to I have to change my code for that to happen?
Upvotes: 2
Views: 3767
Reputation: 887038
Instead of a for
loop or if/else
we can do this with vectorized ifelse
with(MyData, ifelse(Numbers %in% MyVector, paste0("L_N", Numbers), paste0("L_", Numbers)))
#[1] "L_N85" "L_N84" "L_7" "L_9" "L_N82" "L_5" "L_N81" "L_N80" "L_10"
Or with case_when
from dplyr
library(dplyr)
MyData %>%
mutate(Numbers_2 = case_when(Numbers %in% MyVector ~ paste0("L_N", Numbers),
TRUE ~ paste0("L_", Numbers)))
Upvotes: 2