How to count different rows in R

3

I have the following table:

Material    Fornecedor
1   A
1   B
1   A
1   C
1   C
2   B
2   D
2   E
3   A
3   B
3   C
3   F
3   G
3   A
4   A

I need to create a new column of 1 and 0 where 0 will indicate that that vendor has already appeared on that material and 1 will indicate that the vendor first appeared in that material. That is, I will have the following table:

Material    Fornecedor  Qtde
1   A   1
1   B   1
1   A   0
1   C   1
1   C   0
2   B   1
2   D   1
2   E   1
3   A   1
3   B   1
3   C   1
3   F   1
3   G   1
3   A   0
4   A   1

How do I create the Qty column? My data.frame has 560,000 rows.

    
asked by anonymous 29.06.2017 / 20:45

1 answer

1

Follow code for resolution

tab <- data.frame(
  Material = c(rep(1,5), rep(2,3), rep(3,6), 4),
  Fornecedor = c("A","B","A","C","C","B","D","E","A","B","C","F","G","A","A")
)

library(dplyr)
tab %>% 
  mutate(Qtde = ifelse(duplicated(.), 0, 1))
    
29.06.2017 / 21:48