【问题标题】:S3 class Generic and Specific functionsS3 类通用和特定功能
【发布时间】:2015-08-24 16:48:27
【问题描述】:

我想从对象列表中转换一些数据。 我在其中创建了一个通用函数和特定函数,以便它将根据对象的类使用正确的函数。但它似乎并没有从泛型路由到特定功能。如果我输入特定的函数,它会起作用,但它首先破坏了拥有通用函数的目的。

请帮忙。

names <- c("Astro","Barnstormer", "Big Railroad","Buzz", "Soak Station", "Cin.       Castle", 
       "Jamboree", "Dumbo", "Enchanted", "Haunted Mansion", "Jungle Cruise", "Mad Tea", 
       "Aladdin", "Winnie","Monsters, Inc", "Peter Pan", "7 Dwarfs", "Space Mountain")

Letters <-  LETTERS[1:20]

#Giving it different classes
items <- list(names=names, letters=Letters)
class(items$names) <- append(class(items$names), "names ")
class(items$letters) <- append(class(items$letters), "letters")
class(items) <- append(class(items),"items") 

# Generic method
setNames <- function(x, newValue)
{
   print("Find the correct method")
   UseMethod("setNames", x)
 }

#Default method
 setNames.Default <- function(x)
{
   print("You got it wrong")
   return(x)
}

#Specific method to class
 setNames.names <- function(x, newValue)
 {
    x$names <- newValue
    return(x)
 }

  # This works
 t <- setNames.names(items, "abc")
  # This doesn't work. 
 t <- setNames(items, "abc")

【问题讨论】:

  • (1)"names "中有一个尾随空格; (2) 你是 appending 新的类属性而不是 prepending 它们(R 将基于 first 匹配类而不是 最后); (3) 您在 list 对象上调用 setNames 泛型。尝试改用class(items) &lt;- c("names", class(items)); setNames(items, "abc")

标签: r function


【解决方案1】:

我将items 的类设置为c("names", "list"),并对您的函数进行了一些更改。这是否符合您的预期?

#Giving it different classes
items <- list(names=names, letters=Letters)
class(items) <- c("names", "list")

"setNames" <- function(x, ...) {
  UseMethod("setNames")
}


setNames.names <- function(x, newValue) {
  x$names <- newValue
  return(x)
}

setNames.default <- function(x, ...)
{
   warning("unknown class")
   return(x)
}

# This works
t <- setNames.names(items, "abc")

# Check if it works 
t2 <- setNames(items, "abc")

identical(t, t2)
[1] TRUE

还有一个不起作用的情况

foo <- items
class(foo) <- "list"

setNames(foo, "abc")
$names
 [1] "Astro"             "Barnstormer"       "Big Railroad"     
 [4] "Buzz"              "Soak Station"      "Cin.       Castle"
 [7] "Jamboree"          "Dumbo"             "Enchanted"        
[10] "Haunted Mansion"   "Jungle Cruise"     "Mad Tea"          
[13] "Aladdin"           "Winnie"            "Monsters, Inc"    
[16] "Peter Pan"         "7 Dwarfs"          "Space Mountain"   

$letters
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T"

Warning message:
In setNames.default(foo, "abc") : unknown class

【讨论】:

  • 是的,这就是我要找的。谢谢!
  • 我们山姆必须团结在一起!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2017-08-15
  • 2020-07-23
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多