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

时间:2019-02-18 17:21:14

标签: r gsub stringr

我想要的是用序列向量替换占位符%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 )
}

1 个答案:

答案 0 :(得分:2)

您可以使用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"