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

How do I create a new function that iterates a function I previously made in 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 函数来唱整个 song.This 函数需要有三个参数。基本上这样做:

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 必须是单个字符串,而不是 class glue/character 和长度 2 的向量”

如果我更改第二个函数以在 cat() 中包含 glue() 它可以解决该问题,但我会收到一条错误消息,指出“错误:结果 1 必须是字符串,而不是长度为 NULL 0. 此更改还以我不想要的格式提供输出。

而不是使用 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")