【问题标题】:Output of function that is supposed to be input of another function应该是另一个函数输入的函数的输出
【发布时间】:2016-05-31 02:29:00
【问题描述】:

所以,我有一个函数:

 complete <- function(directory,id = 1:332 ) { 
 directory <- list.files(path="......a") 
 g <- list() 
 for(i in 1:length(directory)) { 
  g[[i]] <- read.csv(directory[i],header=TRUE) 
 } 
  rbg <- do.call(rbind,g) 

 rbgr <- na.omit(rbg)   #reads files and omits NA's

 complete_subset <- subset(rbgr,rbgr$ID %in% id,select = ID) 
 table.rbgr <- sapply(complete_subset,table) 
  table.rbd <- data.frame(table.rbgr) 
   id.table <- c(id) 
   findla.tb <- cbind (id.table,table.rbd) 
   names(findla.tb) <- c("id","nob") 
   print(findla.tb)  #creates table with number of observations
} 

基本上当你调用特定的数字 id(比如 4)时, 你应该得到这个输出

 id  nobs 
  15 328 

所以,如果 nobs 值大于另一个任意确定的值 (T),我只需要将 nobs 数据输入另一个函数,该函数测量两列之间的相关性。由于 nobs 是由 id 的值决定的,我不确定如何创建一个考虑到其他函数输出的函数?

我尝试过这样的事情:

corr <- function (directory, t) {
 directory <- list.files(path=".......")
 g <- list()
 for(i in 1:length(directory)) {

 g[[i]] <- read.csv(directory[i],header=TRUE)

  } 

  rbg <- do.call(rbind,g)
  g.all <- na.omit(rbg)  #reads files and removes observations

   source(".....complete.R") #sourcing the complete function above
    complete("spec",id)  
   g.allse <- subset(g.all,g.all$ID %in% id,scol )
   g.allnit <- subset(g.all,g.all$ID %in% id,nit )
   for(g.all$ID %in% id) {  
     if(id > t) {
        cor(g.allse,g.allnit)  #calcualte correlation of these two columns if  they have similar id 
     }
   }
   #basically for each id that matches the ID in g.all function, if the  id > t variable, calculate the correlation between columns 
  }
complete("spec", 3)
cr <- corr("spec", 150)
head(cr)

我也尝试将完整的函数设置为 data.frame,但它不起作用,它给了我以下错误: data.frame(... check.names = false) 参数中的错误意味着行数不同。所以,我不知道如何继续......

【问题讨论】:

    标签: r function output


    【解决方案1】:

    首先,reproducible example 总是有助于回答您的问题,并清楚地解释您的功能做什么/应该做什么。我们无法运行您的示例代码。

    接下来,您的corr 函数似乎有错误。您对id 进行了多次引用,但从未在示例代码中实际填充此变量。所以我们只需要猜测您需要什么帮助。

    认为你想要做的是:

    1. 给定一个id,用那个id打电话给complete
    2. 在您的代码中使用 nobs

    在这种情况下,您需要确保将调用的输出存储到complete,例如

    comp <- complete('spec', id)
    

    您可以通过comp['nobs'] 访问id 列值comp['id']nobs 值,以便您可以执行例如

    if (comp['nobs'] > t) {
        # do stuff e.g.
        cor(g.allse, g.allnit)
    } 
    

    如果您希望稍后真正取回 cor 的输出,请确保将其 存储

    您必须自己解决id 未被定义的问题,因为不清楚您想要它是什么。

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2016-02-07
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2014-11-20
      相关资源
      最近更新 更多