do.call("["...) R 中的函数

do.call("["...) function in R

我正在学习 R,如果我的问题听起来太基础了,我很抱歉。这是我编写的用于从 table 创建 subtable 的函数。我正在关注 Norman Matloff 的书。所以,如果您认为有更短的方法可以做到这一点,我再次感到抱歉。我现在正在学习,所以更长的方法只会帮助我确认我对 R

的理解
subtable <- function(tbl,subnames)
{
  tblarray <- unclass(tbl)
  dcargs <-list(tblarray)
  ndims <- length(subnames) # number of dimensions
  for(i in 1:ndims)
  {
    dcargs[[i+1]]<-subnames[[i]]
  }
  subarray <-do.call("[",dcargs) ###LINE1###
  dims <-lapply (subnames,length)
  subtbl<-array(subarray,dims,dimnames = subnames)
  class(subtbl)<-"table"
  return(subtbl)
}

现在当我调用函数时使用:

ct<-read.table("ct.dat",header=T)

其中 ct.dat 是:

"Vote.for.X" "Voted.for.X.Last.Time"
"Yes" "Yes"
"Yes" "No"
"No" "No"
"Not Sure" "Yes"
"No" "No"

现在,我会打电话给

cttable<-table(ct)
subtable(cttable,subnames<-list(Vote.for.X=c("No","Yes"), Voted.for.X.Last.Time=c("No","Yes"))

我得到了正确的子table。但是,我不知道 LINE1 在做什么。

我逐行执行代码以查看发生了什么。这是调用 for 循环后得到的结果:

> dcargs
[[1]]
          Voted.for.X.Last.Time
Vote.for.X No Yes
  No        2   0
  Not Sure  0   1
  Yes       1   1

[[2]]
[1] "No"  "Yes"

[[3]]
[1] "No"  "Yes"

现在,我知道 dcargs 将是“[”的函数参数。除此之外,我不知道 LINE 1 是怎么回事。我真的被困住了。

有什么帮助吗?

除了@thelatemail 的精彩评论,您还可以从帮助页面 help('[') 获得更多信息,其中显示

indexing by [ is similar to atomic vectors and selects a list of the specified element(s)

我们从函数 do.call 的帮助中读到

do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

此行调用带有列表参数 dcargs 的 [ 函数(之所以命名是因为它们是 do.call 个参数)。由于 dcargs 的元素是 table 的索引,此行正在做的是引用列表对象的相关索引,包含在 [[2]] 和 [[3]] 中,它将索引.

简而言之,do.call("[",dcargs) 索引 dcargs[[1]] 的 no 和 yes 行以及 no 和 yes 列。