Replace rows in a data frame based on criteria

前端 未结 2 778
醉梦人生
醉梦人生 2021-01-06 23:21

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 (i

2条回答
  •  囚心锁ツ
    2021-01-06 23:53

    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)
    

提交回复
热议问题