'changing values in the data frame r studio
I'm struggling a lot right now and it would be great if someone could help me to fix the problem for my master thesis.
I have a huge data frame because heart rates were measured by seconds. The details:
- I have 4 timepoints (timepoint 0, timepoint 1, timepoint 2 and timepoint 3).
- Timepoint 1 to 3 consist of 661 rows each (661 seconds per timepoint).
- Timepoint 0 only refers to one row, but the problem is that it starts with second 1 instead of second 0.
What I want is, that timepoint 0 shows second 0 and timepoint 1 shows second 1 and so on. For better understanding, here are two tables showing the old version and the desired version I'd like to have (not in excel but in r studio):


Atm I'm only able to replace the TS_0 = 1 with TS_0 = 0 for timepoint 0 but I cannot change every row manually afterwards by using df$TS_0[df$TS_0 == 1] <- 0, df$TS_0[df$TS_0 == 2] <- 1 and so on...
My question is, is there anyway to change TS_0 = 1 to 0 with timepoint = 0 so that all the following rows change automatically?
I appreciate any help! Thank you :)
Solution 1:[1]
Not sure what the format is of TS_0 here I demo with a simple 1 column data.table, where it are strings.
dt <- data.table(
TS_0 = c("1 second", paste(3:10, "seconds"))
)
dt[, TS_0 := duration(TS_0) - 1][, timepoint := as.numeric(TS_0) - shift(as.numeric(TS_0), fill = 0L, type = "lag")]
dt
# TS_0 timepoint
# 1: 0s 0
# 2: 2s 2
# 3: 3s 1
# 4: 4s 1
# 5: 5s 1
# 6: 6s 1
# 7: 7s 1
# 8: 8s 1
# 9: 9s 1
- When you make it a duration, you can easily substract 1 to start with 0.
- timepoint you calculate using the lag (note I skipped the 1s row in my example so we get 2 there instead of 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Merijn van Tilborg |
