Home > Back-end >  How to reorder a database after changes
How to reorder a database after changes

Time:12-13

Hello I am working with R and I have a table like this

Sequence Employ
1-0 Lucas
1-1 Juan
2-1 Martin
UNDO
1-2 Pedro

I have a sequence and other field with other data, so what I want to do it´s

  • Filter a new table where the sequence that where delete by the undo it´s cleared, have 1 like this, what commands or filters could I use for this
Sequence Employ
1-0 Lucas
1-1 Juan
1-2 Pedro
  • If the original employee was Martin and no Pedro, how can I have a best clear table with the correct sequence but the employ be the first that appeared, no the final one. Like this
Sequence Employ
1-0 Lucas
1-1 Juan
1-2 Martin
  • The commands that switch this sequence could be "Undo" or "Clear", how can I know what command was between the sequence, like in this example know that the command was Undo without go to check in the original database.

Thanks

I tried to create a extra column with a index increasing and going down when an undo appear, so for example this was the result

Sequence Employ Order
1-0 Lucas 1
1-1 Juan 2
2-1 Martin 3
UNDO 2
1-2 Pedro 3

But failed because I don´t how to select only the second 3 that appear

CodePudding user response:

Excuse the mess of the nested if statement and for loop. This was the fastest thing that came to mind.

df <- data.frame(Sequence =c("1-0","1-1","2-1","UNDO","1-2"),
                 Employ = c("Lucas","Juan","Martin", "", "Pedro"))

# Make a new column
df$Order <- NA
# Index
index<-0

for(i in 1:nrow(df)){
  if(df$Sequence[i]!="UNDO"){
    index <- index 1
    df$Order[i]<- index
  } else{
    if(index-1 > 0){
      index <- index-1
      df$Order[i]<- index
    } else{
      df$Order[i]<-0
    }
  }
}

df

Sequence Employ Order
1      1-0  Lucas     1
2      1-1   Juan     2
3      2-1 Martin     3
4     UNDO            2
5      1-2  Pedro     3

CodePudding user response:

df[-(which(df$Sequence == "UNDO")   (-1):0),]
#  Sequence Employ
#1      1-0  Lucas
#2      1-1   Juan
#5      1-2  Pedro

pos <- which(df$Sequence == "UNDO")
data.frame(Sequence = df$Sequence[-(pos   (-1):0)], 
           Employ = df$Employ[-(pos   0:1)])
#  Sequence Employ
#1      1-0  Lucas
#2      1-1   Juan
#3      1-2 Martin
  • Related