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

R: How to search for a row by a condition, and then change that row?

Say we have a data.frame as follows,

name<-c("alison","bob","carol","dave")
age<-c(30,31,32,33)
hairlength<-c(1500,300,1400,500)
data<-data.frame(name,age,hairlength)

Let’s say I have many, many rows of data and I want to search for the row that contains "bob" and change the hair length in this row from 300 to 350. So that if I view the data.frame, the hair length has been changed. How do I go about that simple process?

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

>Solution :

One way to do this is as follows. We match every row within data that has character string bob in column name and assign the value 350 to the column hairlength of that specific row.

data[data$name %in% 'bob', ]$hairlength <- 350

Output

> data
    name age hairlength
1 alison  30       1500
2    bob  31        350
3  carol  32       1400
4   dave  33        500
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