使用 sprintf 而不是粘贴来折叠字符向量 [英] Collapsing character vectors with sprintf instead of paste

查看:54
本文介绍了使用 sprintf 而不是粘贴来折叠字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去我主要使用 pastepaste0 来完成我的粘贴任务,但我对 sprintf 的速度非常着迷.但我觉得我缺乏一些基础知识.

I have mostly used paste or paste0 for my pasting tasks in the past, but I'm pretty fascinated by the speed of sprintf. Yet I feel that I'm lacking some its basics.

只是想知道是否还有一种方法可以将多元素字符向量折叠为长度为 1 的字符向量,就像 paste 在使用其 collapse 参数时所做的那样,即,无需手动指定相应的通配符及其值(在粘贴中,我只是将任务留给函数来确定应该折叠多少个元素).>

Just wondered if there's also a way to collapse a multi-element character vector to one of length 1 as paste would do when using its collapse argument, that is, without having to specify respective wildcards and its values manually (in paste, I simply leave the task up to the function to find out how many elements should be collapsed).

x <- c("Pasted string:", "hello", "world!")

> sprintf("%s %s %s", x[1], x[2], x[3])
[1] "Pasted string: hello world!"
> paste(x, collapse=" ")
[1] "Pasted string: hello world!"

我正在寻找这样的东西(伪代码)

I'm looking for something like this (pseudo code)

> sprintf("<the-correct-parameter>", x)
[1] "Pasted string: hello world"

<小时>

感兴趣的:sprintfpaste

require("microbenchmark")
t1 <- median(microbenchmark(sprintf("%s %s %s", x[1], x[2], x[3]))$time)
t2 <- median(microbenchmark(paste(x, collapse=" "))$time)

> t1/t2
[1] 0.7273114

推荐答案

函数 sprintf 回收其格式字符串,例如代码

The function sprintf recycles its format string, so for example the code

cat(sprintf("%8.4f",rnorm(5)),"\n")

打印类似的东西

-0.5685 -0.6481 0.6296 -0.0043 -1.4763

-0.5685 -0.6481 0.6296 -0.0043 -1.4763

str = sprintf("%8.4f",rnorm(5))

将输出存储在字符串向量中

stores the output in a vector of strings and

str_one = paste(sprintf("%8.4f",rnorm(5)),collapse='')

将输出存储在单个字符串中.格式字符串不需要指定要打印的浮点数.这也适用于打印 %d 和 %s 格式的整数和字符串.

stores the output in a single string. The format string does not need to specify the number of floats to be printed. This also holds for printing integers and strings with the %d and %s formats.

这篇关于使用 sprintf 而不是粘贴来折叠字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆