r语言 - 在分配多个类时改变变量的类型



我正在处理r中的一些S3方法,我为它们创建了一个类系统,一切都很好。然而,有时不同类型的对象是有问题的,我偶然发现只有在分配单个类时类型才会改变,而不是多个类,更不用说非基类了。

如何强制改变类的类型?最好是自动/立即安全计算时间。

x <- 1L
class(x)
#> [1] "integer"
typeof(x)
#> [1] "integer"
# assigning one class chages the type accordingly
class(x) <- "character"
class(x)
#> [1] "character"
typeof(x)
#> [1] "character"
# assigning multiple classes does not change the type
x <- 1L
class(x) <- c("character", "foo")
class(x)
#> [1] "character" "foo"
typeof(x) # should be character
#> [1] "integer"
# actual goal would be to change the type by the first 
# known class - type tandem
x <- 1L
class(x) <- c("foo", "character")
class(x)
#> [1] "foo"       "character"
typeof(x) # should be character
#> [1] "integer"

执行更改最好通过as.character或任何其他as.xxxxxx函数完成。换班就是自找麻烦。此外,as.xxxxxx将返回一个错误,如果某些东西不像预期的那样工作。更改类不会产生任何错误,可能会导致代码失败。

。data.frame属于data.frame类,但typeof是一个列表。将list的类更改为data.frame并不能正确地将其更改为data.frame。但是,如果你通过类将列表更改为data.frame,它不会给出错误,但结果可能不是你想要的。

的例子:

my_list <- list(a = c(letters[1:4]),
b = c(letters[5:7]))
# error
as.data.frame(my_list)
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
arguments imply differing number of rows: 4, 3
# wrong results                    
class(my_list) <- "data.frame"
is.data.frame(my_list)
TRUE
my_list
[1] a b
<0 rows> (or 0-length row.names)

添加你自己的类是非常方便的,因为你可以用它来检查函数内部和输出。

想了解更多信息,我建议阅读下面的文章,了解class和typeof的区别,以及其中的R手册链接:

对R中事物类型的全面调查;& # 39;模式# 39;和& # 39;类# 39;和& # 39;typeof # 39;不足

变量的类型和类

https://stats.stackexchange.com/questions/3212/mode-class-and-type-of-r-objects

最新更新