How to compare values of the same variable and generate another variable that has the result of this comparison in R

Asked

Viewed 30 times

0

I have to reproduce this formula I made in Excel =SE(C2=C1;1+D1;1) to R, but I don’t know how.

I have a basis where one of the variables is the position of employees, and I need to create a variable that lists the positions that are equal, that way:

Cargo (Coluna C)         Numero do Cargo (Coluna D)

Analista de BI                   1
Coordenador de Dados             1
Analista de BI                   2  
Analista de Dados                1
Analista de BI                   3 

I need to create this column Numero do Cargo. How to do it in R?

  • You have to tell us what the columns are C and D in this data example (which only has 2 columns, A and B should not be for sure).

  • Hey, I put the description on the table.

1 answer

3


Here is a solution in a line with ave and seq_along.

dados$Numero.do.Cargo.2 <- as.integer(ave(dados$Cargo, dados$Cargo, FUN = seq_along))

As you can see, the third column is identical to the second.


This problem arises from time to time, the following function can be applied directly to the base and to the column that defines the groups.

seq_by_group <- function(x, col){
  col <- deparse(substitute(col))
  x_col <- as.character(x[[col]])
  y <- ave(x_col, x_col, FUN = seq_along)
  as.integer(y)
}

seq_by_group(dados, Cargo)
#[1] 1 1 2 1 3

Dice

dados <-
structure(list(Cargo = c("Analista de BI", 
"Coordenador de Dados", "Analista de BI", 
"Analista de Dados", "Analista de BI"), 
Numero.do.Cargo = c(1L, 1L, 2L, 1L, 3L)), 
class = "data.frame", row.names = c(NA, -5L))
  • Thank you for the answer! The application worked perfectly to solve my problem.

Browser other questions tagged

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