Replace rows in a data frame based on criteria

前端 未结 2 781
醉梦人生
醉梦人生 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:46

    Here's another approach (taking into account @DWin's comment)

    dfrm <- data.frame(id=letters[1:3], f1=c(1,3,4), f2=c(3,5,7))
    
    dfrm[dfrm$f1>3, -1] <- 0
    levels(dfrm$id) <- c(levels(dfrm$id), 'x')
    dfrm[,1]<- with(dfrm, replace(id, f1==0, 'x')) ; dfrm
    
         id f1 f2
      1  a  1  3
      2  b  3  5
      3  x  0  0
    

    Using some more data:

    set.seed(007); N <- 12
     f1 <- sample(1:9, N, replace=TRUE)
     f2 <- sample(1:9, N, replace=TRUE)
     dfrm2 <- data.frame(id=letters[1:N], f1=f1, f2=f2)
    
     dfrm2[dfrm2$f1>3, -1] <- 0
     levels(dfrm2$id) <- c(levels(dfrm2$id), 'x')
     dfrm2[,1]<- with(dfrm2, replace(id, f1==0, 'x')) ; dfrm2
       id f1 f2
    1   x  0  0
    2   x  0  0
    3   c  2  5
    4   d  1  1
    5   e  3  6
    6   x  0  0
    7   x  0  0
    8   x  0  0
    9   i  2  6
    10  x  0  0
    11  k  2  9
    12  l  3  9
    

    I deleted my previous code, because they weren't useful for this question.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题