Let's say I have the following data frame:
Seconds = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3)
Markers= c("NA", "NA", "Start", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA")
df = data.frame(Seconds, Markers)
I want to move the value indicated by 'Start' in column Markers down its column (or a new column) a difference of 0.5 Seconds. Where this could be one result:
Seconds = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3)
Markers2= c("NA", "NA", "NA", "NA", "NA", "NA", "NA", "Seconds", "NA", "NA", "NA", "NA", "NA", "NA")
df2 = data.frame(Seconds, Markers2)
Or this would work to if it's easier to accomplish:
Seconds = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3)
Markers2= c("NA", "NA", "NA", "NA", "NA", "NA", "NA", "Seconds", "NA", "NA", "NA", "NA", "NA", "NA")
df3 = data.frame(Seconds, Markers, Markers2)
I thought maybe I could do something like this:
df$MarkerReal <- NA
df$MarkerReal [which(df$Markers == 'Start') + 5] <- 'Start'
This works for this example, but the real data I'm working with is time sensitive in milliseconds with thousands of rows. There isn't a specified amount of rows I need to move it, but rather base it off the value, in this example moving it by half a second.
Any ideas?
Here is an option:
curr.pos <- which(df$Markers == "Start")[[1]] # taking first "Start" in case you have more than one
new.pos <- with(df, max(which(Seconds <= Seconds[[curr.pos]] + 0.5)))
df$Markers[c(curr.pos, new.pos)] <- c("NA", "Start")
Produces:
Seconds Markers
1 0.0 NA
2 0.1 NA
3 0.2 NA
4 0.3 NA
5 0.4 NA
6 0.5 NA
7 0.6 NA
8 0.7 Start
9 0.8 NA
10 0.9 NA
11 1.0 NA
12 1.1 NA
13 1.2 NA
14 1.3 NA
This of course assumes your DF is sorted by the Seconds
column.
As a side note, you should consider using real NAs (ie NA_character_
) as opposed to strings with an "NA" value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.