我正在编写一个用于加密小短语的函数,最终得到了初始短语 (
w0
) 及其加密版本 (w1
)。
我想将
w0
和 w1
输入到函数返回的对象中,我目前正在使用 list()
执行此操作
但是,如果我将其保存在一个对象中(在代码中称为 TEST)然后调用它,则初始短语和加密短语都会被打印,这对我来说不是最佳选择。
我希望能够将输出保存在一个对象中,当天真地调用时,它只会显示第一个元素(初始单词),并且可以在具体需要时打印第二个元素,也许使用
$
.
这可能吗? 谢谢!
我当前的功能是
list()
cipher <- function(word){
w0 <- tolower(unlist(strsplit(word, "")))
w1 <- c()
shuffledletters <- sample(letters)
for (i in (1:length(w0))) {
w1[i] <- ifelse(w0[i] %in% letters,
shuffledletters[which(w0[i]==letters)], " ")
}
out <- list(w0,w1)
return(out)
}
我现在得到的:
TEST <- cipher("hello world")
TEST
[[1]]
[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"
[[2]]
[1] "p" "s" "r" "r" "a" " " "y" "a" "j" "r" "m"
我想要的输出(我知道对于列表这是不可能的)
TEST
[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"
TEST$initial
[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"
TEST$encrypted
[1] "p" "s" "r" "r" "a" " " "y" "a" "j" "r" "m"
这似乎是一个使用自定义打印方法创建自己的类的好例子(参见
?class
)。例如:
cipher <- function(word){
w0 <- tolower(unlist(strsplit(word, "")))
w1 <- c()
shuffledletters <- sample(letters)
for (i in (1:length(w0))) {
w1[i] <- ifelse(w0[i] %in% letters,
shuffledletters[which(w0[i]==letters)], " ")
}
out <- list(initial=w0,encrypted=w1)
class(out) <- "cipher"
return(out)
}
print.cipher <- function(x,...){
print.default(x$initial, ...)
}
TEST <- cipher("hello world")
TEST
# [1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"
TEST$initial
# [1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"
TEST$encrypted
# [1] "s" "d" "x" "x" "r" " " "g" "r" "a" "x" "p"