R在函数内调用函数

时间:2014-09-08 18:25:31

标签: r

Airlines_Dataset <- function(Number_Of_Rows){

#Departure Date
day.start <- "2009/01/01"
day.end <- "2014/04/25"

Departure_Date <- function(day.start,day.end,size) { //Generates Random dates
    dayseq <- seq.Date(as.Date(day.start),as.Date(day.end),by="day")
    dayselect <- sample(dayseq,size,replace=TRUE)
    Date <- dayselect
}
Date <- data.frame(Departure_Date(day.start,day.end,size=Number_Of_Rows))
return(Date)


#Origin
Origin_Func <- function(Number_Of_Rows,...){
Origin <- (sample(c('IND','ISP','JAN','JAX','IND','ISP',
    'LAS','LAX','LBB','LIT','MAF','MCI','MCO','MDW','MHT',
'MST','MCO','OAK','OAC','OMA','OMT','ORF','PBI','PDX',
'PHL','PHX','PIT','PVD','RDU','RNO','RSW','SAN','SAT',
'SDF','SEA','SFO','SJC','SLC','SMF','SNA','STL','TPA',
'TUL','TUS','ABQ','IAD'),Number_Of_Rows, replace=TRUE))

Origin <- data.frame(Origin)
/*Given below is source code of origin*/   
 Origin_Exec <-     system.time((sample(c('IND','ISP','JAN','JAX','IND','ISP',
    'LAS','LAX','LBB','LIT','MAF','MCI','MCO','MDW','MHT',
    'MST','MCO','OAK','OAC','OMA','OMT','ORF','PBI','PDX',
    'PHL','PHX','PIT','PVD','RDU','RNO','RSW','SAN','SAT',
    'SDF','SEA','SFO','SJC','SLC','SMF','SNA','STL','TPA',
    'TUL','TUS','ABQ','IAD'),Number_Of_Rows, replace=TRUE)))
}
/*Some static origin codes that generates random strings from the list given above*/
return(Origin)

}

正在调用下面给出的函数

Airlines_Result <- Airlines_Dataset(1000)

当我调用上面的函数时,只调用了一个函数,即没有调用date和tine origin。

最后一步是组合数据框

Airlines_Data <- data.frame(Origin,Date)

任何人都可以帮助以正确的格式执行代码我希望在单个函数调用中存在原点和日期

1 个答案:

答案 0 :(得分:0)

我重新编写了代码并添加了一些代码。在您的情况下,您不需要嵌套函数。要在函数内调用函数,请分别编写内部函数。外部函数调用所有其他函数:

Departure_Date <- function(day.start,day.end,size) 
{ 
  dayseq <- seq.Date(as.Date(day.start),as.Date(day.end),by="day")
  dayselect <- sample(dayseq,size,replace=TRUE)
  Date <- dayselect

  return(Date)

}


  #Origin
Origin_Func <- function(Number_Of_Rows)
{
    Origin <- (sample(c('IND','ISP','JAN','JAX','IND','ISP',
                        'LAS','LAX','LBB','LIT','MAF','MCI','MCO','MDW','MHT',
                        'MST','MCO','OAK','OAC','OMA','OMT','ORF','PBI','PDX',
                        'PHL','PHX','PIT','PVD','RDU','RNO','RSW','SAN','SAT',
                        'SDF','SEA','SFO','SJC','SLC','SMF','SNA','STL','TPA',
                        'TUL','TUS','ABQ','IAD'),Number_Of_Rows, replace=TRUE))

    return(Origin)
}


Airlines_Dataset <- function(day.start ="2009/01/01", day.end = "2014/04/25", Number_Of_Rows=1000)
{  
  Data <- data.frame(Departure_Date(day.start,day.end,Number_Of_Rows),Origin_Func(Number_Of_Rows))
  names(Data) = c("Date", "Origin")
  return(Data)
}


Airlines_Result = Airlines_Dataset()