1

我对 S3 很陌生,想知道是否有可能给出以下数据框:

test <- tibble(
  elements = c("one", "two", "three"),
  S3 = c("foo", "bar", "foo")
)

我可以给列中的每个元素elements一个来自 S3 列的自定义类:

custom_class <- function(x, customclass) {
  class(x) <- c(class(x), customclass)
  return(x)
}

# test
s <- "string"
custom_class(s, "anything")
test <- tibble(
  elements = c("one", "two", "three"),
  S3 = c("foo", "bar", "foo"),
  testing = custom_class(elements, S3)
)

但这不起作用。这是由于我对 S3 的理解存在心理模型差距吗?是否可以以这种方式对每个元素应用不同的类,如果不能,可以以某种方式将输出创建为列表,以便列表中的每个元素都是一个elementwith class S3?任何提示/帮助建议表示赞赏!

4

2 回答 2

1

另一种选择是rowwise如果我们想坚持dplyr

library(dplyr)
tibble(
  elements = c("one", "two", "three"),
   S3 = c("foo", "bar", "foo")) %>% 
    rowwise %>%
    mutate(test = list(custom_class(elements, S3)))
# A tibble: 3 x 3
# Rowwise: 
#  elements S3    test      
#  <chr>    <chr> <list>    
#1 one      foo   <charactr>
#2 two      bar   <charactr>
#3 three    foo   <charactr>
于 2020-04-18T19:35:03.787 回答
1

通过c在数据框上使用,所有属性都将丢失。我们可以通过在数据框中创建一个列表列来保留任何自定义属性:

test <- tibble(
  elements = c("one", "two", "three"),
  S3 = c("foo", "bar", "foo"),
  test = map2(elements, S3, ~ custom_class(.x, .y))
)
于 2020-04-18T17:12:16.600 回答