2013-10-24 37 views
0

我正在嘗試創建一個函數,該函數需要三個參數才能完成作業,並嘗試過幾次,但沒有運氣!非常感謝一些建議或幫助:)如何用三個參數創建一個函數

我已經創建了以下內容:

##### 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 

這是我的家庭作業的最後一題的一個,我只是完全停留在所有:(

我真的不知道從哪裏開始。

任何人都可以請能夠給我一些建議或支持,請?

+0

家庭作業,因此只提示:您可以使用該「NZ1」參數來提取您的矩陣的子集:'newmat < - boatlist [boatlist [1] ==「NZ1」,]'並繼續與在'newmat'中的時間列[ –

回答

0

我不認爲你需要三個參數,因爲你的三個參數是相互關聯的,即當指定船時,它在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) 

對不起,如果我誤解了你的問題,但。

+0

]對不起 - 我快速瀏覽了代碼。 –

0

由於這是一個家庭作業闕這可能不會爲任何人直接回答它。

有關功能的更多信息,請參閱Quick-R/User-defined functions

與該函數什麼也不做,但返回他們串聯三個參數的函數的一個例子:

myfunc <- function(first, second, third) { 
return(cat(first, second, third)) 
} 

您可以調用爲myfunc("foo","bar","baz"),並得到結果「富酒吧巴茲」。