How to edit the value in the dataframe based on a condition in R?

I want to add an asterisk (*) to values in a data frame based on condition. I wrote the following dataframe:

ID Var1 Var2
A 9 45.50
B 20 89.99
C 5 14.50
D 11 15.50
E 9 50.99

I want to add a (*) to Var2 values if Var1 value is smaller than 10. I wrote the following code:

    DF1 = data.frame(ID=c("A","B","C","D","E"), 
    DF1$Var2[DF1$Var1<10] <- paste0(DF1$Var2,"*")

The problem is when I do this, I get the following error:

Warning message:
In DF1$Var2[DF1$Var1<10] <- paste0(DF1$Var2, :
number of items to replace is not a multiple of replacement length

And the output is the following:

enter image description here

Does anyone know how to fix this or have a better method to do this? Thanks!

>Solution :

You just have to also filter your right hand side to the same number of rows.

DF1 = data.frame(ID=c("A","B","C","D","E"), 
DF1$Var2[DF1$Var1 < 10] <- paste0(DF1$Var2[DF1$Var1 < 10],"*")

Leave a Reply