为什么我的自定义S3类对象不能追加到R中的列表中?

oymdgrw7  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(99)

我正在学习如何在R中定制s3类,遇到了一个令人挠头的问题。
在创建了我的自定义S3类的一个示例之后,它不会用c()追加到list。没有显示警告或错误,它只是不追加,我不知道为什么。
输入:

# initialize a list and observe expected results
    my_list <- list()

my_list

输出:

list()

输入:

# Append to the list with c() as per usual and observe expected results
    my_list <- c(my_list, 1)

my_list

输出:

[[1]]
[1] 1

输入:

my_list <- c(my_list, 2)

my_list

输出:

[[1]]
[1] 1

[[2]]
[1] 2

输入:

# Define my custom S3 class
    my_custom_s3_class <- function(attribute1, attribute2) {
        my_custom_s3_class <- structure(list(), class = "my_custom_s3_class")
        attributes(my_custom_s3_class)$attribute1 <- attribute1
        attributes(my_custom_s3_class)$attribute2 <- attribute2
        my_custom_s3_class
    }

# Define print method for my S3 class
    print.my_custom_s3_class <- function(x, ...) {
        cat(attributes(x)$attribute1, attributes(x)$attribute2)
    }

# Create an instance of my custom S3 class and observe expected results when calling it
    my_custom_object <- my_custom_s3_class("hello", "world")
    my_custom_object

输出:

hello world

输入:

# Attempt to append my custom S3 class to my list from before and observe no warnings or error messages
    my_list <- c(my_list, my_custom_object)

# Observe that it was not appended
    my_list

输出:

[[1]]
[1] 1

[[2]]
[1] 2
gr8qqesn

gr8qqesn1#

对象的长度为0

length(my_custom_object)
[1] 0

所以我们需要把它 Package 在一个list

c(my_list, list(my_custom_object))
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
hello world

相关问题