R 如何创建具有三个参数的函数
我正在尝试创建一个函数,其中包含三个参数作为我的家庭作业,并且已经尝试了好几次,但没有成功!非常感谢您的建议或帮助:) 我已经创建了以下内容:R 如何创建具有三个参数的函数,r,R,我正在尝试创建一个函数,其中包含三个参数作为我的家庭作业,并且已经尝试了好几次,但没有成功!非常感谢您的建议或帮助:) 我已经创建了以下内容: ##### 1) > raceIDs [1] "GER" "SUI" "NZ2" "US1" "US2" "POR" "FRA" "AUS" "NZ1" "SWE" ##### 2) #For each "raceIDs", there is a csv file which I have made a loop to read and crea
##### 1)
> raceIDs
[1] "GER" "SUI" "NZ2" "US1" "US2" "POR" "FRA" "AUS" "NZ1" "SWE"
##### 2)
#For each "raceIDs", there is a csv file which I have made a loop to read and created a list of data frames (assigned to the symbol "boatList")
#For example, if I select "NZ1" the output is:
> head(boatList[[9]]) #Only selected the first six lines as there is more than 30000 rows
Boat Date Secs LocalTime SOG
1 NZ1 01:09:2013 38150.0 10:35:49.997 22.17
2 NZ1 01:09:2013 38150.2 10:35:50.197 22.19
3 NZ1 01:09:2013 38150.4 10:35:50.397 22.02
4 NZ1 01:09:2013 38150.6 10:35:50.597 21.90
5 NZ1 01:09:2013 38150.8 10:35:50.797 21.84
6 NZ1 01:09:2013 38151.0 10:35:50.997 21.95
##### 3)
# A matrix showing the race times for each raceIDs
> raceTimes
start finish
GER "11:10:02" "11:35:05"
SUI "11:10:02" "11:35:22"
NZ2 "11:10:02" "11:34:12"
US1 "11:10:01" "11:33:29"
US2 "11:10:01" "11:36:05"
POR "11:10:02" "11:34:31"
FRA "11:10:02" "11:34:45"
AUS "11:10:03" "11:36:48"
NZ1 "11:10:01" "11:35:16"
SWE "11:10:03" "11:35:08"
我需要做的是,我需要计算一艘船“在比赛时”(在开始和结束时间之间)的平均速度(SOG)
基本上,我需要做一个类似的函数:
> meanRaceSpeed("NZ1", boatList, raceTimes)
[1] 18.32
> meanRaceSpeed("US1", boatList, raceTimes)
[1] 17.23
这是我作业的最后一个问题,我完全被卡住了:(
我甚至不知道从哪里开始
有谁能给我一些建议或支持吗?因为这是一个家庭作业问题,直接回答可能对任何人都没有好处 有关功能的更多信息,请参见例如 一个具有三个参数的函数示例,该函数不执行任何操作,只返回串联的参数:
myfunc <- function(first, second, third) {
return(cat(first, second, third))
}
myfunc我认为您不需要三个参数,因为您的三个参数是相互关联的,即当指定了一条船时,也可以指定它在boatList
中的位置,也可以指定它的raceTimes
我没有测试以下函数,因为模拟随机数据有点痛苦,但我相信这可能会有所帮助:
meanRaceSpeed <- function(x) #`x` is the boat's name
{
start_time <- raceTimes$start[rownames(raceTimes) == x]
finish_time <- raceTimes$finish[rownames(raceTimes) == x]
#which `LocalTime` is the first with `start_time`
start_LocalTime <- min(grep(start_time, boatList[[x]]$LocalTime))
#which `LocalTime` is the last with `finish _time`
#(if you want the first `finish_time` change `max` with `min`)
finish_LocalTime <- max(grep(finish_time, boatList[[x]]$LocalTime))
#which `SOG`s contain all the `LocalTimes` between start and finish
#take their `mean`
mean(boatList[[x]]$SOG[start_LocalTime : finish_LocalTime])
}
#for all boats, something like:
sapply(raceIDs, meanRaceSpeed)
meanRaceSpeed作业,因此仅提示:您可以使用“NZ1”参数提取矩阵的子集:newmat