MariKo MariKo - 3 months ago 9
R Question

Copy the value of a row in the previous row R

I have a big dataset df; its short version looks like this:

Time Block Accuracy
6087.8 Run2 NA
633.2 Run2 NA
547 Run2 incorrect
135.2 Run2 NA
6217.6 Run2 NA
175.2 Run2 NA
179 Run2 incorrect


I want to copy the value incorrect in the previous row of df$Accuracy, so it would look like this:

Time Block Accuracy
6087.8 Run2 NA
633.2 Run2 incorrect
547 Run2 incorrect
135.2 Run2 NA
6217.6 Run2 NA
175.2 Run2 incorrect
179 Run2 incorrect


What is the most efficient way to do it?

Answer

To see the rows that will be affected, run:

which(df$Accuracy == "incorrect")-1 

which() returns the elements of a vector that are true for a particular boolean statement (in this case, which values of Accuracy are equal to incorrect). We then minus 1 from each value in the vector to get the previous row positions.

We can then modify them:

df[which(df$Accuracy == "incorrect")-1, "Accuracy"] <- "incorrect"

This finds all the rows as above, and says: for those rows and the column "Accuracy", replace the values with "incorrect".