我想从对象列表中转换一些数据。我创建了一个通用函数和特定的函数,这样它就会根据对象的类别使用正确的函数。但它似乎没有从通用到特定的功能。如果我输入一个特定的函数,它可以工作,但它首先违背了使用泛型函数的目的。
请帮助。
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")
我将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