R: return 我函数中的对象列表不是 return 预期的列表

R: return list of objects in my function does not return expected list

我在 R 中编写了一个函数来 return 并集、交集、一组中最常见的词和唯一的词。它 return 是一个包含四个预期结果的列表。但是,当我从另一个程序(错误的)调用函数时得到的结果与我逐行 运行 函数(正确的)时得到的结果不同。

WordSet_operations <- function(df)

  df <- gsub(",", " ", df) 
  aux<- docTerm(df) # returns DocumentTermMatrix (tm)
  aux<- aux %>% 
    select(sort(tidyselect::peek_vars())) #columns in alphabetical order
  
  inputsets<- length(df)
  
  #Union
  unionterms<- colnames(aux) #La funcion docTerm ya funde los términos iguales

  #Intersection
  if (inputsets %in% colSums(aux))  { 
    indexintersect<-which(colSums(aux)==inputsets) 
    intersectterms <- colnames(aux[indexintersect])
  } else intersectterms <- NA 
  
  #Common terms
  indexcomunes<-which(colSums(aux)>0.5*max(colSums(aux))) 
  commonterms<- colnames(aux[indexcomunes]) #heuristical threshold 0.5
  
   #Unique terms
  indexunicos<-which(colSums(aux)==1)
  uniqueterms<- colnames(aux[indexunicos])
  
return(list(unionterms, intersectterms, commonterms, uniqueterms))

在我点击 return 行之前,该函数可以正常工作。 return行的数据结构是正确的,但是主程序得到的结果不对。

我已经对一个迷你数据框进行了子集化来说明问题:

 dput(df)
c("Biomaterials ElectronicOpticalMagneticMaterials Energy MaterialsChemistry SurfacesCoatingsFilms", 
"CondensedMatterPhysics MaterialsScience", "CeramicsComposites MaterialsChemistry OrganicChemistry PolymersPlastics SurfacesInterfaces", 
"Bioengineering Chemistry CondensedMatterPhysics MaterialsScience MechanicalEngineering NanoscienceNanotechnology"
)

如果我将它提供给函数


result <- WordSet_operations(df)
dput(result)
c("Biomaterials ElectronicOpticalMagneticMaterials Energy MaterialsChemistry SurfacesCoatingsFilms", 
"CondensedMatterPhysics MaterialsScience", "CeramicsComposites MaterialsChemistry OrganicChemistry PolymersPlastics SurfacesInterfaces", 
"Bioengineering Chemistry CondensedMatterPhysics MaterialsScience MechanicalEngineering NanoscienceNanotechnology"
)

如果我进入函数内部并逐行执行代码,在 return 行我有

dput(list(unionterms, intersectterms, commonterms, uniqueterms))
list(c("bioengineering", "biomaterials", "ceramicscomposites", 
"chemistry", "condensedmatterphysics", "electronicopticalmagneticmaterials", 
"energy", "materialschemistry", "materialsscience", "mechanicalengineering", 
"nanosciencenanotechnology", "organicchemistry", "polymersplastics", 
"surfacescoatingsfilms", "surfacesinterfaces"), NA, c("condensedmatterphysics", 
"materialschemistry", "materialsscience"), c("bioengineering", 
"biomaterials", "ceramicscomposites", "chemistry", "electronicopticalmagneticmaterials", 
"energy", "mechanicalengineering", "nanosciencenanotechnology", 
"organicchemistry", "polymersplastics", "surfacescoatingsfilms", 
"surfacesinterfaces"))

您可以检查这个是否正确,因为输入词向量的交集实际上为空(我的函数中为 NA)。我期待函数 return 正是这个(我已经多次获取该文件以防它被遗忘,但它 return 每次都是同样的问题)

我想我遗漏了一些非常明显的东西(抱歉,如果这是一个愚蠢的问题),但我对这种“return”行为感到困惑。有什么想法吗?

您缺少 {} 来定义函数。我想这就是为什么 R 没有意识到您想要函数内部的输出。 你应该试试。

 function_name <- function(arg_1, arg_2, ...) {
   Function body 
}