【发布时间】: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) <- c("names", class(items)); setNames(items, "abc")。