我如何创建一个新函数来迭代我以前在R中创建的函数?



我必须创建3个函数来演唱圣诞节的12天。第一个函数生成一个短语。

make_phrase <- function(num, gift) {
if (!is.character(gift[1])) {
stop("Gift should be a string of characters") }
if (!is.numeric(num[1])) {
stop("Num should be a number") }
num <- as.character(english(num))
num <- ifelse(num == "one", "a", num)
glue("{num} {gift}")
}

第二个函数使用第一个函数创建歌曲的一节。

sing_verse <- function(num, day, gift) {
day <- day[num]
daily_phrase <- make_phrase(num:1, gift[num:1])
cat("On the", day, "day of Christmas, my true love gave to me, n")
glue("{daily_phrase}")
}

这两个函数似乎都可以工作,我想创建第三个函数,它使用sing_verse函数来演唱整首歌。这个函数需要有三个参数。基本上是这样做的:

sing_verse(1, xmas$day_in_words, xmas$gift_item)
sing_verse(2, xmas$day_in_words, xmas$gift_item)
sing_verse(3, xmas$day_in_words, xmas$gift_item)
sing_verse(4, xmas$day_in_words, xmas$gift_item)
sing_verse(5, xmas$day_in_words, xmas$gift_item)
sing_verse(6, xmas$day_in_words, xmas$gift_item)
sing_verse(7, xmas$day_in_words, xmas$gift_item)
sing_verse(8, xmas$day_in_words, xmas$gift_item)
sing_verse(9, xmas$day_in_words, xmas$gift_item)
sing_verse(10, xmas$day_in_words, xmas$gift_item)
sing_verse(11, xmas$day_in_words, xmas$gift_item)
sing_verse(12, xmas$day_in_words, xmas$gift_item)

我试过了:

sing_xmas_song <- function(days, names, gifts) {
verses<- map_chr(days, ~sing_verse(.x, names, gifts)) %>%
cat(sep = "n")
return(verses)
}

但是我收到了一个错误,"错误:结果2必须是单个字符串,而不是类glue/character且长度为2的向量">

如果我更改第二个函数以在cat()中包含glue(),则解决了该问题,但我随后得到一个错误,声明&;error: Result 1必须是一个字符串,而不是长度为0的NULL。此更改还以我不想要的格式输出。

与其用glue代替daily_phrase,还不如直接用print

make_phrase <- function(num, gift) {
if (!is.character(gift[1])) {
stop("Gift should be a string of characters") }
if (!is.numeric(num[1])) {
stop("Num should be a number") }
num <- as.character(english(num))
num <- ifelse(num == "one", "a", num)
glue("{num} {gift}")
}

sing_verse <- function(num, day, gift) {
day <- day[num]
daily_phrase <- make_phrase(num:1, gift[num:1]) 

cat(paste("On the", day, "day of Christmas, my true love gave to me, n"))
print(daily_phrase)
}
现在,调用for循环
for(i in 1:3) sing_verse(i, xmas$day_in_words, xmas$gift_item)
On the first day of Christmas, my true love gave to me, 
a partridge in a pear tree
On the second day of Christmas, my true love gave to me, 
two turtle doves
a partridge in a pear tree
On the third day of Christmas, my true love gave to me, 
three french hens
two turtle doves
a partridge in a pear tree

数据
xmas <- structure(list(day = 1:6, day_in_words = c("first", "second", 
"third", "fourth", "fifth", "sixth"), gift_item = c("partridge in a pear tree", 
"turtle doves", "french hens", "calling birds", "golden rings", 
"geese a-laying")), row.names = c(NA, 6L), class = "data.frame")

最新更新