samedi 13 janvier 2018

Adding characters/letters to value based on condition

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?

Aucun commentaire:

Enregistrer un commentaire