gpt4 book ai didi

r - 如何用 r 中的序列替换替换可变数量的占位符?

转载 作者:行者123 更新时间:2023-12-05 05:12:17 25 4
gpt4 key购买 nike

我想要的是用序列向量替换占位符 %f。我目前正在使用 stringr 函数,但对于每个占位符,我必须添加额外的替换向量。问题是,测试字符串中占位符的数量是可变的。我下面的代码不是很优雅,它固定为 8 个占位符。有什么方法可以使用 stringr 或任何其他库使它更加动态吗?

sequence = seq(-10, 10, by = 0.001)

if (str_count(equation, "%f") == 1) {
input_equations <-sprintf(equation, sequence )
}
else if (str_count(equation, "%f") == 2) {
input_equations <-sprintf(equation, sequence, sequence )
}
else if (str_count(equation, "%f") == 3) {
input_equations <-sprintf(equation, sequence, sequence, sequence )
}
else if (str_count(equation, "%f") == 4) {
input_equations <-sprintf(equation, sequence, sequence, sequence, sequence )
}
else if (str_count(equation, "%f") == 5) {
input_equations <-sprintf(equation, sequence, sequence, sequence, sequence, sequence )
}
else if (str_count(equation, "%f") == 6) {
input_equations <-sprintf(equation, sequence, sequence, sequence, sequence, sequence, sequence )
}
else if (str_count(equation, "%f") == 7) {
input_equations <-sprintf(equation, sequence, sequence, sequence, sequence, sequence, sequence, sequence )
}
else if (str_count(equation, "%f") == 8) {
input_equations <-sprintf(equation, sequence, sequence, sequence, sequence, sequence, sequence, sequence, sequence )
}

最佳答案

您可以使用 do.call 函数来完成。您将需要一个参数列表。所以代码是:

# Example equation and sequence
equation <- "a + %f - %f"
sequence <- c(1:3)

# Get number of placeholders
str_n <- str_count(equation, "%f")
# Construct arguments list
arg_list <- lapply(c(1:str_n), function(x) sequence)
arg_list$fmt <- equation # Named argument

# Call sprintf with constructed arguments
input_equations <- do.call("sprintf", arg_list)

结果如下:

[1] "a + 1.000000 - 1.000000" "a + 2.000000 - 2.000000"
[3] "a + 3.000000 - 3.000000"

关于r - 如何用 r 中的序列替换替换可变数量的占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54752384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com