繁体   English   中英

我正在为R中的函数寻求通配符,但不知道搜索什么?

[英]I'm seeking a wildcard character for my function in R, but don't know what to search?

可复制的例子

我寻求构建一个函数来基于数据子集构建回归。 我的可复制示例如下:

set.seed(1) # Reproducibility

testdat <- data.frame(x = runif(100),
                      y = rnorm(100),
                      factor = sample(c("A","B"),100,replace=T)) # Create a dummy data set

test.model <- function(input.factor = NULL){
  model.out = lm(y~x,data = testdat[which(testdat$factor == input.factor),])
} # Create a function that regresses x against y, after subsetting

modelA <- test.model(input.factor = "A") # Works fine
modelB <- test.model(input.factor = "B") # Also works fine
modelAll <- test.model(input.factor = "???") # I'm seeking the keyword for all the data here

问题

对于input.factor = "A""B"情况,我的函数工作正常,但我想在整个数据集上使用该函数。 我试过使用*通配符,但这似乎仅对正则表达式有效。

我的问题是, 我需要在input.factor =键入什么字符串才能选择factor变量的所有值?

PS:作为一名统计学家,我知道我应该在回归本身中包括factor变量。 但是,我的实际用例是具有更多数据的更复杂的模型,因此计算完整的模型会花费太多时间。

我会这样做:

test.model <- function(input.factor = NULL){
  if (is.null(input.factor)){
    model.out = lm(y~x,data = testdata)
  } else{
    model.out = lm(y~x,data = testdat[which(testdat$factor == input.factor),])
  }
 model.out
} #

正如@Ronak指出的那样,您必须进行2次更改。

函数调用test.model和您的“通配符”。 *是SQL-synthax,但是您可以使用unique()来请求数据集中的所有唯一名称。

set.seed(1) # Reproducibility

testdat <- data.frame(x = runif(100),
                      y = rnorm(100),
                      factor = sample(c("A","B"),100,replace=T)) # Create a dummy data set

test.model <- function(input.factor = NULL){
  model.out = lm(y~x,data = testdat[which(testdat$factor %in% input.factor),])
} # Create a function that regresses x against y, after subsetting

modelA <- test.model(input.factor = "A") # Works fine
modelB <- test.model(input.factor = "B") # Also works fine
modelAll <- test.model(input.factor = unique(testdat$factor))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM