如何在R中的另一个函数中运行函数?

时间:2018-07-02 15:23:06

标签: r function

我看到了一个与此类似的问题,但我并不完全理解答案。这是我的原始功能:

fxn_import_data <- function(file_path, filen)
    {work <-setwd(file_path)
    yelp <- stream_in(file(filen)) #creating a data fram called yelp using stream_in function}
    #head(yelp, 10)
    yelp_flat<- flatten(yelp) #helps turn JSON files with multiple df's into tabular format
    #str(yelp_flat) #displays abbreviated content (not needed for this data set)
    scoop <- as_data_frame(yelp_flat)
}

此功能的目的是打开数据的文件源并解压缩它。我需要这些数据来运行我的下一个功能,如下所示:

fxn_create_meta<- function(fxn_import_data, scoop) {return(scoop)
fxn_import_data <- function(file_path, filen)
  scoop <- as_data_frame(yelp_flat)
  scoop$homePlayers <- NULL #eliminates homePlayers column
  scoop$awayPlayers <- NULL
  pop <- scoop %>% separate(ball, c("ball_x", "ball_y", "ball_z"), sep = ",") 
  #separates one column into multiple 
  l <- pop %>% separate(ball_x, c("throw","ball_x"), sep = "c")
  gh <- l %>% separate(ball_z, c("ball_z", "tra"), sep = "\\)")
  Meta <- gh %>% separate(ball_x, c("kol", "ball_x"), sep = "\\(")
  Meta$tra <- NULL
  Meta$kol <- NULL
  Meta$throw <- NULL
  return(Meta)
}

但是,当我尝试运行第二个函数时,它告诉我对象“ scoop”未定义。我该如何解决?

1 个答案:

答案 0 :(得分:2)

您可以编写两个函数,第二个函数在其中运行第一个函数:

fxn_import_data <- function(file_path, filen)
    {work <-setwd(file_path)
    yelp <- stream_in(file(filen))
    yelp_flat<- flatten(yelp)
    scoop <- as_data_frame(yelp_flat)
}


fxn_import_data <- function(file_path, filen){
  scoop <- fxn_import_data(file_path, filen)#RUN THE FIRST FUNCTION AND SAVE THE RESULT AS scoop
  scoop$homePlayers <- NULL
  scoop$awayPlayers <- NULL
  pop <- scoop %>% separate(ball, c("ball_x", "ball_y", "ball_z"), sep = ",")       l <- pop %>% separate(ball_x, c("throw","ball_x"), sep = "c")
  gh <- l %>% separate(ball_z, c("ball_z", "tra"), sep = "\\)")
  Meta <- gh %>% separate(ball_x, c("kol", "ball_x"), sep = "\\(")
  Meta$tra <- NULL
  Meta$kol <- NULL
  Meta$throw <- NULL
  return(Meta)
}

请阅读评论