R 如何否定子集论点
我正在编写一个函数,它对数据帧进行t测试,根据我定义的参数对数据进行子集设置。以下是使用mtcars数据的工作示例:R 如何否定子集论点,r,null,arguments,subset,t-test,R,Null,Arguments,Subset,T Test,我正在编写一个函数,它对数据帧进行t测试,根据我定义的参数对数据进行子集设置。以下是使用mtcars数据的工作示例: testfunc <- function(dfrm, varq, factor, gear = FALSE, am = FALSE, carb = FALSE){ # Subset the data according to the arguments: subsetdfrm <- dfrm[which((dfrm[,
testfunc <- function(dfrm, varq, factor, gear = FALSE,
am = FALSE, carb = FALSE){
# Subset the data according to the arguments:
subsetdfrm <- dfrm[which((dfrm[,"gear"] %in% gear) &
(dfrm[,"am"] %in% am) &
(dfrm[,"carb"] %in% carb)),]
# Grab the groups to be compared according to arguments:
factorbinary <- get(factor)
# The t-test:
t <- t.test(dfrm[which(dfrm[factor]==factorbinary[1]), varq],
dfrm[which(dfrm[factor]==factorbinary[2]), varq],
data = subsetdfrm)
print(t)
}
注意,我将参数的默认值定义为“FALSE”。我想要的是为这些参数找到一个默认值,它会自动否定子集,这意味着包含所有值。
我自己的最佳解决方案是在函数开头为每个参数添加if()子句,如下所示:
if(carb == FALSE){gear <- unique(dfrm$gear)}
if(am == FALSE){am <- unique(dfrm$am)}
if(carb == FALSE){carb <- unique(dfrm$carb)}
if(carb==FALSE){gear根据Frank在评论中的贡献,下面是一个可行的解决方案:
testfunc <- function(dfrm, varq, factor, gear = unique(dfrm$gear),
am = unique(dfrm$am), carb = unique(dfrm$carb)){
# Subset the data according to the arguments:
subsetdfrm <- dfrm[which((dfrm[,"gear"] %in% gear) &
(dfrm[,"am"] %in% am) &
(dfrm[,"carb"] %in% carb)),]
# Grab the groups to be compared according to arguments:
factorbinary <- get(factor)
# The t-test:
t <- t.test(dfrm[which(dfrm[factor]==factorbinary[1]), varq],
dfrm[which(dfrm[factor]==factorbinary[2]), varq],
data = subsetdfrm)
print(t)
}
testfunc根据Frank在评论中的贡献,以下是一个可行的解决方案:
testfunc <- function(dfrm, varq, factor, gear = unique(dfrm$gear),
am = unique(dfrm$am), carb = unique(dfrm$carb)){
# Subset the data according to the arguments:
subsetdfrm <- dfrm[which((dfrm[,"gear"] %in% gear) &
(dfrm[,"am"] %in% am) &
(dfrm[,"carb"] %in% carb)),]
# Grab the groups to be compared according to arguments:
factorbinary <- get(factor)
# The t-test:
t <- t.test(dfrm[which(dfrm[factor]==factorbinary[1]), varq],
dfrm[which(dfrm[factor]==factorbinary[2]), varq],
data = subsetdfrm)
print(t)
}
testfunc如果你有一个行索引向量(比如返回的),你可以用-
,选择补码来求反。哦,我知道你的意思是不子集。为此,你可以在函数(…)中写gear=unique(dfrm$gear)
part。由于R的惰性求值,它只会在函数内部需要时求值这个术语。我们在看哪个模块?这是一个很长的页面,也许我可以ctrl-F一个关键字,带我到您所指的部分?我指的是“索引向量”第节,抱歉。但考虑到你的“否定”概念不是我所假设的,这不相关。我从未考虑过在参数中加入gear=unique(dfrm$gear)
,我觉得这正是我需要的解决方案!如果你有一个行索引向量(比如返回的),您可以使用-
,选择补码来否定它们。请看,哦,我明白您的意思是不使用子集。为此,您只需在函数(…)中编写gear=unique(dfrm$gear)
part。由于R的惰性求值,它只会在函数内部需要时求值这个术语。我们在看哪个模块?这是一个很长的页面,也许我可以ctrl-F一个关键字,带我到您所指的部分?我指的是“索引向量”抱歉,这与你的“否定”概念无关。我从未考虑过在参数中加入gear=unique(dfrm$gear)
,我觉得这正是我需要的解决方案!