How to count different lines in R

Asked

Viewed 695 times

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 supplier has already appeared in that material and 1 will indicate that the supplier appeared for the first time in that material. I mean, I’ll 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 Qtde column? My data.frame has 560,000 rows.

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))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.