使用函数存储在全局环境中的策略

Strategies for using functions to store within the global env

假设我们有以下数据框:

# Data
Id <- c(1,2,3,4,5,6,7,8,9,10)
Type <- c("Beginner", "Expert", "Intermediate", "Beginner", 
  "Professional", "Expert", "Intermediate", "Professional", 
  "Professional", "Expert")
Response<- c(1,1,2,2,1,2,1,2,1,1)
Successful <- data.frame(Id, Type, Response)
Successful

# Dataframe
#   Successful
Id  Type             Response    
1   Beginner         1
2   Expert           1
3   Intermediate     2
4   Beginner         2
5   Professional     1
6   Expert           2
7   Intermediate     1
8   Professional     2
9   Professional     1
10  Expert           1

我知道我可以通过执行以下操作将其作为对象 (DFRespType) 存储在全局环境中:

 DFRespType <- 
  as.data.frame(round(100*prop.table(table(Successful$Response, 
                                   Successful$Type),2), 1))

但相反,我想创建一个函数来存储对象,以提高执行此操作的效率。下面我尝试制作 StoreDF 函数:

StoreDF <- function(DFName, dataset, variable1, variable2){
  DFName <- as.data.frame(round(100*prop.table(table(dataset$variable1, 
                                              dataset$variable2),2), 1))
}

但是当我尝试按以下方式使用它时,没有存储任何内容:

StoreDF(DFRespType, Successful, Response, Type)

如有任何帮助,我们将不胜感激。

不要在函数内部将对象存储在全局环境中。相反 return 从函数返回的数据帧。还使用带引号的变量对数据框进行子集化。

StoreDF <- function(dataset, variable1, variable2){
    as.data.frame(round(100* prop.table(table(dataset[[variable1]], 
                        dataset[[variable2]]),2), 1))
}

DFRespType <- StoreDF(Successful, "Response", "Type")
DFRespType

#  Var1         Var2 Freq
#1    1     Beginner 50.0
#2    2     Beginner 50.0
#3    1       Expert 66.7
#4    2       Expert 33.3
#5    1 Intermediate 50.0
#6    2 Intermediate 50.0
#7    1 Professional 66.7
#8    2 Professional 33.3