Home > database >  row_number() gives a non-obvious result
row_number() gives a non-obvious result

Time:08-04

b.set <- 1
df <- data.frame (co = c(2.3,3.1,5.7), factor = c(3,5,6))%>% 
  mutate (a = 1,
          b = ifelse (b.set == 1, row_number() 10-1, 0),
  ) 

I get the following result:

   co factor a  b
1 2.3      3 1 10
2 3.1      5 1 10
3 5.7      6 1 10

I would like the end result to be as follows

   co factor a  b
1 2.3      3 1 10
2 3.1      5 1 11
3 5.7      6 1 12

I'm pretty sure it worked fine yesterday.

CodePudding user response:

Here, we need if/else as ifelse requires all arguments to be of same length - b.set is of length 1, where as the 'yes' is of length 3

library(dplyr)
data.frame (co = c(2.3,3.1,5.7), factor = c(3,5,6))%>%
     mutate(a = 1, b = if(b.set == 1) row_number()   10 -1 else 0)

-output

   co factor a  b
1 2.3      3 1 10
2 3.1      5 1 11
3 5.7      6 1 12
  • Related