如何编写在数值中包含前导零的 substr 版本(在 R 中)?
How to code a substr version that holds leading zeros in numeric values (in R)?
在准备将规范化双精度数转换为十进制数的函数时,我需要如下内容:
substr(01001011, 2, 5) # what is in fact:"0010" (because leading 0 is ignored)
substr(01001011, 2, 5) # what I want:"1001"
substr("01001011", 2, 5) # "1001"; gives what I want BUT the following:
在 substr("01001011", 2, 5)
中,(对我而言)不可能将其转换为函数,因为 input=01001011
和双引号连接非常非常有问题。每次用户都必须手动输入参数值,而不是在函数调用中,而是在 substr(...)
部分所在的函数体中。
由于 01001011
被保留为数字而导致的问题,因此所有前导 0 都被忽略。
01001011 # [1] 1001011
class(01001011) # "numeric"
substrCorrectly <- function(x) {
substr("x", 2, 5) }
例如,对于号码“01001011”;
substrCorrectly <- function(x) {
substr("01001011", 2, 5) }
substrCorrectly(01001011) # "1001"
这个函数绝对是丑陋的,违背了函数的概念:每次用户必须在应用之前改变函数体!
有什么想法吗?
更多示例:
substr(000101001011, 1, 4) # "1010"; but what I want is 0001 here.
substr(10001, 1, 2) # "10" and what I want (10) coincides since 1 is leading.
您可以使用 formatC
这将允许先保留 0s
substrCorrectly <- function(x) {
x <- formatC(x, flag="0", width=8, format="d")
substr(x, 2, 5)
}
substrCorrectly(01001011) # "1001"
在准备将规范化双精度数转换为十进制数的函数时,我需要如下内容:
substr(01001011, 2, 5) # what is in fact:"0010" (because leading 0 is ignored)
substr(01001011, 2, 5) # what I want:"1001"
substr("01001011", 2, 5) # "1001"; gives what I want BUT the following:
在 substr("01001011", 2, 5)
中,(对我而言)不可能将其转换为函数,因为 input=01001011
和双引号连接非常非常有问题。每次用户都必须手动输入参数值,而不是在函数调用中,而是在 substr(...)
部分所在的函数体中。
由于 01001011
被保留为数字而导致的问题,因此所有前导 0 都被忽略。
01001011 # [1] 1001011
class(01001011) # "numeric"
substrCorrectly <- function(x) {
substr("x", 2, 5) }
例如,对于号码“01001011”;
substrCorrectly <- function(x) {
substr("01001011", 2, 5) }
substrCorrectly(01001011) # "1001"
这个函数绝对是丑陋的,违背了函数的概念:每次用户必须在应用之前改变函数体!
有什么想法吗?
更多示例:
substr(000101001011, 1, 4) # "1010"; but what I want is 0001 here.
substr(10001, 1, 2) # "10" and what I want (10) coincides since 1 is leading.
您可以使用 formatC
这将允许先保留 0s
substrCorrectly <- function(x) {
x <- formatC(x, flag="0", width=8, format="d")
substr(x, 2, 5)
}
substrCorrectly(01001011) # "1001"