Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"), 
                 Var1=c(9,20,5,11,9), 
                 Var2=c("45.50","89.99","14.50","15.50","50.99"), 
    DF1$Var2[DF1$Var1<10] <- paste0(DF1$Var2,"*")

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"), 
             Var1=c(9,20,5,11,9), 
             Var2=c("45.50","89.99","14.50","15.50","50.99"))
DF1$Var2[DF1$Var1 < 10] <- paste0(DF1$Var2[DF1$Var1 < 10],"*")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading