I have 2 dataframes. The first, I'm calling "tableA" has a start time, stop time, and number associated with it (there is a lot more columns but these are the only relevant ones). My second df is "tableB" and has a timestamp. Here is some example data:
tableA <- data.frame("start" = 1:5, "stop"= 2:6, "numb" = 11:15)
tableB <- data.frame("timeStamp" = c(1.7, 2.1, 2.4, 2.8, 4.5), "numb" = 0)
Which would result in frames looking like this:
tableA tableB
start stop numb timeStamp numb
1 2 11 1.7 0
2 3 12 2.1 0
3 4 13 2.4 0
4 5 14 2.8 0
5 6 15 4.5 0
I'm trying to label all of the timestamps in tableB with the corresponding number in tableA when it falls in between a start and stop time. For example, for the first row in tableB (1.7), it would get the number 11 (since it falls between 1 and 2). So for this data, I'd want tableB to look like this:
tableB
timeStamp numb
1.7 11
2.1 12
2.4 12
2.8 12
4.5 14
So to do this, I wrote the following nested loop statement:
for(n in 1:length(tableB$timeStamp)) {
for(i in 1:length(tableA$numb)) {
if(tableB$timeStamp[n] > tableA$start[i] &
tableB$timeStamp[n] < tableA$stop[i]) {
tableB$numb[n] <- tableA$numb[i]
sprintf("n = %i", n)
sprintf("i = %i", i)}
}
}
However, all of the values in tableB$numb are just getting changed to 5 and there is nothing being printed to the console. I'm not sure what I've messed up here, since it seems to never even get in the if statement and yet tableB$numb are being updated incorrectly. Any hints or help would be much appreciated!
Aucun commentaire:
Enregistrer un commentaire