S3类通用和特定功能

时间:2015-08-24 16:48:28

标签: r function

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

请帮忙。

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")

0 个答案:

没有答案
相关问题