首页 > 解决方案 > 如何创建一个新函数来迭代我以前在 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() 中包含胶水(),它可以解决该问题,但随后我会收到一条错误消息,指出“错误:结果 1 必须是字符串,而不是长度为 0 的 NULL。此更改也以我不想要的格式给出输出。

标签: rfunctioniteration

解决方案


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

推荐阅读