【问题标题】:我们能找到基础 R 中的所有类吗?
【发布时间】:2022-01-23 09:58:18
【问题描述】:

有没有办法获取在基础 R 中定义的所有类?我的预期输出是一个包含类名的字符向量。像这样的:

"character" "factor" "function" "dataframe" "list" ...

背景:我制作了一个应该应用于尽可能多的类的函数。我无法详细解释我在做什么,但请考虑像 str 这样的函数,据我所知可以应用于任何类。另一方面,像sum 这样的函数需要特定的输入,即数字输入。我想知道所有预定义的类,以便我可以看到我的函数在哪些类上有效,哪些无效。

【问题讨论】:

  • 类只不过是对象上的字符串属性。 S3 类可以使用任何名称作为类名。我假设“base R”也指默认包,如statsutilsgraphics。那里有很多课程。例如class(as.person("Joe Smith"))。据我所知,没有主名单。您在寻找对象的哪些属性?
  • “考虑像 str 这样的函数,据我所知可以应用于任何类” str 是 S3 泛型。默认方法适用于所有模式。如果你想让它为一个类做任何特定的事情,你需要为str定义一个方法。
  • 您可以查看base packagesNAMESPACE 文件中的S3method 条目。
  • 您可能会发现.S3_methods_table 很有帮助。
  • 这是有用的提示。尤其是来自@jay.sf 的.S3_methods_table 很棒!

标签: r class


【解决方案1】:

即使sum 支持的功能超出您的想象,它也会变得棘手,还取决于class 您在matrixarray 上遇到问题,您还需要使用typeof 来查看例如,如果它的内容是numeric, integer。另请注意,NA 默认被视为logicalNULL 提供NULL 类。

这里有一些关于不同类变量及其行为的示例,sum

a <- 1L
class(a)
[1] "integer"

b <- 1
class(b)
[1] "numeric"

c <- FALSE
class(c)
[1] "logical"

d <- as.factor(1L)
class(d)
[1] "factor"

e <- matrix(1:2)
class(e)
[1] "matrix"
typeof(e)
[1] "integer"

f <- c(1:2)
class(f)
[1] "integer"

g <- NA
class(g)
[1] "logical"

h <- NULL
class(h)
[1] "NULL"

i <- -Inf
class(i)
[1] "numeric"

j <- array(1:2)
class(j)
[1] "array"
typeof(j)
[1] "integer"

class(sum(a, a))
[1] "integer"

class(sum(a, b))
[1] "numeric"

class(sum(b, b))
[1] "numeric"

class(sum(c, c))
[1] "integer"

class(sum(c, a))
[1] "integer"

class(sum(c, b))
[1] "numeric"

class(sum(d + d))
[1] "integer"
Warning message:
In Ops.factor(d, d) : ‘+’ not meaningful for factors

class(sum(d, d))
Error in Summary.factor(1L, 1L, na.rm = FALSE) : 
  ‘sum’ not meaningful for factors

class(sum(e, d))
[1] "integer"

class(sum(e, e))
[1] "integer"

class(sum(f, f))
[1] "integer"

class(sum(g, h))
[1] "integer"

class(sum(h, h))
[1] "integer"

class(sum(i, i))
[1] "numeric"

class(sum(e, j))
[1] "integer"

【讨论】:

  • 这很有趣,但不幸的是,我的问题与sum 函数无关。我只是作为一个例子提到它。我也可以写meansd 等等。事实上,问题是关于基础 R 中的预定义类。
  • 我同意这不是您问题的答案,但它是相关的,特别是类与 typeof 之类的数据数组或矩阵以及函数如何在它们上运行。我宁愿将其发布在 cmets 中,而不是作为答案,但由于其格式和长度,无法将其作为评论发布。
【解决方案2】:

1) 假设这是指 S3 类启动一个新会话,加载您想要包含的任何包并运行它:

sort(unique(sub(".*?\\.", "", ls(.__S3MethodsTable__.))))

2) 另一种方法假设这是指包“基础”(如果需要,可以对其他基础包重复)和 S3 类,这会查找基础包中具有一个或它们中有更多点,然后在点之后给出唯一值,如果有一个点,则给出 res1,如果有两个或多个点,则给出 res2,而不是在 res1 中。这只是一个近似值,因此您必须手动检查这些以检查哪些实际上代表了类。

nms <- grep("\\.", ls(asNamespace("base")), value = TRUE)
no_dots <- lengths(gregexpr(".", nms, fixed = TRUE))

res1 <- sort(unique(sub(".*\\.", "", nms[no_dots == 1])))
res2 <- setdiff(sort(unique(sub(".*?\\.", "", nms[no_dots > 1]))), res1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多