Vector version of do for / while loop

I would like to write a cleaner way to do the following:

I have data.frame P (5000rows x 4cols) and would like to find the median values ​​in columns 2,3 and 4 when the timestamp in column 1 falls within the given range defined by the TimeStamp vector (in seconds).

dput(TimeStamp)
c(18, 138, 438, 678, 798, 1278, 1578, 1878, 2178)


dput(head(P))
structure(list(Time = c(0, 5, 100, 200, 500, 1200), SkinTemp = c(27.781, 
27.78, 27.779, 27.779, 27.778, 27.777), HeartRate = c(70, 70, 
70, 70, 70, 70), RespirationRate = c(10, 10, 10, 10, 10, 10)), .Names = c("Time", 
"SkinTemp", "HeartRate", "RespirationRate"), row.names = c(NA, 
6L), class = "data.frame")

eg.

for x<i<y in P[,1]
     find median of all values in P[,2], P[,3] and P[,4]
     Put median values into a new matrix with headers SkinTemp, HeartRate and RespirationRate
end
+4
source share
2 answers

You can try:

aggregate(P[,-1],list(Time=findInterval(P$Time,TimeStamp)),mβ€Œβ€‹edian)  
#  Time SkinTemp HeartRate RespirationRate
#1    0  27.7805        70              10
#2    1  27.7790        70              10
#3    2  27.7790        70              10
#4    3  27.7780        70              10
#5    5  27.7770        70              10

You want to split the values Timeaccording to the interval in which they fall. There is a feature Rthat makes it: findInterval. So, we calculate the interval for each value Time, and then the aggregatevalues ​​of the other columns and calculate median.

+4
source

Another option is to use the function cut

P$new <- cut(P$Time, breaks = c(-Inf, TimeStamp, Inf))
aggregate(. ~ new, P, median)

#             new   Time SkinTemp HeartRate RespirationRate
#1      (-Inf,18]    2.5  27.7805        70              10
#2       (18,138]  100.0  27.7790        70              10
#3      (138,438]  200.0  27.7790        70              10
#4      (438,678]  500.0  27.7780        70              10
#5 (798,1.28e+03] 1200.0  27.7770        70              10
+2

Source: https://habr.com/ru/post/1666349/


All Articles