I am looking to subset a data frame in R. My syntax is obviously wrong (ie producing the wrong results).
data[i,]$m_cnt <- nrow(w_data[
w_data$direction >= data[i,]$min_a &
w_data$direction < data[i,]$max_a &
w_data$windspeed >= 3 &
w_data$windspeed < 15,
])/records;
Similar question: Filtering a data.frame
The w_data data.frame (simplified for brevity) consists of wind speed and wind direction time-series data.
time_stamp windspeed direction
2010-06-01 00:00 12.2 125
2010-06-03 02:50 17.4 312
2010-06-05 21:30 2.1 132
2010-06-12 15:10 7.8 71
2010-06-22 17:40 2.6 307
2010-06-30 03:20 5.1 310
The above R statement is supposed to count the number of records within a certain wind direction range, say for instance >=120°
and <135°
and within a certain wind speed range, in this example >=3m/s
and <15m/s
. The count is then converted into a percentage of the total number of measurements taken, so the above example should be equal to 1 record out of 6 = 16.66%. The percentage is then recorded into another data.frame (data) which has the structure:
min_a max_a l_cnt m_cnt h_cnt
0 15 0 0 0
15 30 0 0 0
30 45 0 0 0
45 60 0 0 0
60 75 0 0.1666 0
75 90 0 0 0
90 105 0 0 0
105 120 0 0 0
120 135 0.1666 0.1666 0
135 150 0 0 0
150 165 0 0 0
165 180 0 0 0
180 195 0 0 0
195 210 0 0 0
210 225 0 0 0
225 240 0 0 0
240 255 0 0 0
255 270 0 0 0
270 285 0 0 0
285 300 0 0 0
300 315 0.1666 0.1666 0.1666
315 330 0 0 0
330 345 0 0 0
345 360 0 0 0
The problem I am experiencing is that the sum of all percentages do not equal 100% (this example does, but not I run my script over 10,000's of records).
I have also experienced weird results, such as:
data[i,]$l_cnt <- nrow(w_data[
w_data$direction >= data[i,]$min_a &
w_data$direction < data[i,]$max_a &
w_data$windspeed <= 3,
])/records;
data[i,]$m_cnt <- nrow(w_data[
w_data$direction >= data[i,]$min_a &
w_data$direction < data[i,]$max_a &
w_data$windspeed <= 15,
])/records;
data[i,]$h_cnt <- nrow(w_data[
w_data$direction >= data[i,]$min_a &
w_data$direction < data[i,]$max_a &
w_data$windspeed > 15,
])/records;
Produces totals of:
l_cnt 0,360637343
m_cnt 0,187836625
h_cnt 0,811938959
total 1,360412926
But if I qualify the m_cnt calculation with a greater than and less than, ie:
data[i,]$m_cnt <- nrow(w_data[
w_data$direction >= data[i,]$min_a &
w_data$direction < data[i,]$max_a &
w_data$windspeed >= 3 &
w_data$windspeed < 15,
])/records;
I get:
l_cnt 0
m_cnt 0,360637343
h_cnt 0,811938959
total 1,172576302