Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace rows in a data frame based on criteria

Tags:

r

I have the following data frame

   id f1 f2
1  a  1  3
2  b  3  5
3  c  4  7

I would like to replace all rows which have f1>3 with a row (id = x, f1 = 0, f2 = 0) So the above would map to

   id f1 f2
1  a  1  3
2  b  3  5
3  x  0  0

But when I tried

replace(x,which(x$f1>3),data.frame(id = 'x',f1=0,f2=0))

It didn't do it right, it gave

   id f1 f2
1  a  1  x
2  b  3  x
3  c  4  x
Warning message:
In `[<-.data.frame`(`*tmp*`, list, value = list(id = 1L, f1 = 0,  :
  provided 3 variables to replace 1 variables

Could someone suggest a way to do this at scale? Thanks.

like image 375
broccoli Avatar asked Sep 09 '26 06:09

broccoli


1 Answers

Something like this:

 x[x$f1 > 3,] <- data.frame('x', 0, 0)

should do the trick!


as per @DWin's comment, this won't work with a factor id column. Using this same technique can work like this though:

levels(x$id) <- c(levels(x$id), 'x')
x[x$f1 > 3,] <- data.frame('x', 0, 0)
droplevels(x$id)
like image 153
Justin Avatar answered Sep 11 '26 20:09

Justin