我有一个数据框,包含关于潮汐的以下信息。我正在尝试编写一个函数,该函数需要四个参数(low.max,hi.max,hi.earliest,hi.latest)。例如,显示所有低潮小于或等于2英尺,高潮小于或等于6英尺,并且高潮发生在上午10点到下午4点之间的日子。目前,我正在通过循环行来完成这个任务(在某种程度上已经可以使用hi.max-low.max),但我对R比较陌生,认为应该有更符合R语言风格的方法。
添加 dput 输出:
date day time ft cm H/L
2013/01/01 Tue 07:03 AM 8.1 247 H
2013/01/01 Tue 12:49 PM 5.1 155 L
2013/01/01 Tue 05:30 PM 5.7 174 H
2013/01/02 Wed 12:03 AM 0.5 15 L
2013/01/02 Wed 07:33 AM 8.1 247 H
2013/01/02 Wed 01:40 PM 4.4 134 L
2013/01/02 Wed 06:32 PM 5.3 162 H
2013/01/03 Thu 12:42 AM 1.4 43 L
2013/01/03 Thu 08:03 AM 8.1 247 H
2013/01/03 Thu 02:33 PM 3.5 107 L
2013/01/03 Thu 07:46 PM 4.9 149 H
添加 dput 输出:
structure(list(Date = structure(c(15706, 15706, 15706, 15707,
15707, 15707, 15707, 15708, 15708, 15708), class = "Date"), Day = c("Tue",
"Tue", "Tue", "Wed", "Wed", "Wed", "Wed", "Thu", "Thu", "Thu"
), Time = c("7:03 AM", "12:49 PM", "5:30 PM", "12:03 AM", "7:33 AM",
"1:40 PM", "6:32 PM", "12:42 AM", "8:03 AM", "2:33 PM"), Pred.Ft. = c(8.1,
5.1, 5.7, 0.5, 8.1, 4.4, 5.3, 1.4, 8.1, 3.5), Pred.cm. = c(247L,
155L, 174L, 15L, 247L, 134L, 162L, 43L, 247L, 107L), High_Low = c("H",
"L", "H", "L", "H", "L", "H", "L", "H", "L")), .Names = c("Date",
"Day", "Time", "Pred.Ft.", "Pred.cm.", "High_Low"), row.names = c(NA,
10L), class = "data.frame")
就 hi/lo 部分而言,独立于时间,我尝试了以下方法:
tides <- read.csv("TideData.csv", stringsAsFactors = FALSE)
for (i in 1: nrow(tides)){
if (tides[i, 6] == "L" & tides[i, 4] <= low.max
& tides[i+1, 6] == "H" & tides[i+1, 4] <= hi.max){
#deal with last iteration being out of bounds / write out to a df
}
dput(head(dat, 11))
,其中dat
是您的数据框。这样可以清楚地查看您的实际数据长什么样子。 - Matthew Lundberg