R语言使用sprintf传入向量提示参数过少,如何得到预期输出
报错原因
sprintf 的参数规则要求模板内有N个占位符,就需要传入N个独立的替换参数。你直接传入一个长度为3的向量,函数会判定你仅传入了1个参数,和模板要求的3个参数数量不匹配,因此触发too few arguments报错。
另外注意模板内的占位符写法要正确,% s中间不能有空格,需要改成%s才能被正确识别。
解决方法
方法1:使用do.call打散参数(基础包方案,无需安装额外依赖)
do.call可以将列表内的元素拆分为独立参数传入目标函数,我们只需要把模板字符串和替换向量都放入同一个列表传入即可:
split_links <- c("<a href=https://google.com>s</a>", "<a href=https://yahoo.com>s</a>" , "<a href=https://google.com>s</a>") # 构造参数列表:第一个元素是模板字符串,后续是拆分后的替换参数 params <- c(list("This is the link %s also there is another link, %s This is the link %s "), as.list(split_links)) result <- do.call(sprintf, params)
运行后输出和你给出的预期结果完全一致。
方法2:使用glue包做字符串插值(写法更直观)
如果可以使用第三方包,glue的字符串插值语法不需要匹配占位符数量,直接在模板内用{}调用变量即可,可读性更高:
# 首次使用需要先安装:install.packages("glue") library(glue) split_links <- c("<a href=https://google.com>s</a>", "<a href=https://yahoo.com>s</a>" , "<a href=https://google.com>s</a>") result <- glue("This is the link {split_links[1]} also there is another link, {split_links[2]} This is the link {split_links[3]} ")
内容的提问来源于stack exchange,提问作者user11740857
相关产品推荐
相关产品推荐

