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

Time:01-17

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?

CodePudding user response:

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
  •  Tags:  
  • Related