如何将数字向量中的非二进制(0/1 除外)字符替换为零(在 R 中)



在创建复杂函数时,我需要将数字向量中的所有非二进制(0/1 除外(字符转换为零:

cwhmisc::int(1010110.001) # 1010110; integer part; class=integer
cwhmisc::frac(1010110.001) # 0.001; fractional part; class=numeric
as.character(cwhmisc::frac(1010110.001)) # "0.00100000004749745" (unwanted nonbinaries (4,7,4,9,7,4,5) produced)
toString(cwhmisc::frac(1010110.001))     # "0.00100000004749745" (was not a solution to kill unwanted things)
nchar(cwhmisc::frac(1010110.001))        # 19 (unwanted things are really there)
as.numeric(strsplit(substr(as.character(cwhmisc::frac(1010110.001)),3,nchar(as.character(cwhmisc::frac(1010110.001)))),"")[[1]]) # 0 0 1 0 0 0 0 0 0 0 4 7 4 9 7 4 5

如何转换

c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 7, 4, 9, 7, 4, 5)
c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

x <- c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 7, 4, 9, 7, 4, 5)
ifelse(x == 0 | x == 1, x, 0)
# [1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0

你也可以做:

x * (x == 1)
 [1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0

为了完整起见,我添加了Andrew Gustar的解决方案:

gsub("[^1]", "0", cwhmisc::frac(1010110.001)) # "0000100000000000000"
noOfchars <- nchar(gsub("[^1]", "0", cwhmisc::frac(1010110.001))) # 19
substr( gsub("[^1]", "0", cwhmisc::frac(1010110.001)), 3, noOfchars) # [1] "00100000000000000". Remove leading "0."

gsub(模式、替换、字符串(:替换模式匹配和替换中的所有匹配项。
pattern:包含正则表达式(或固定 = TRUE 的字符串(的字符串,要在给定的字符向量中匹配。

"[^1]"

替换:"0"
寻求匹配项的字符向量:

cwhmisc::frac(1010110.001) # 0.001  

(注:options(digits=22); cwhmisc::frac(1010110.001) # 0.0010000000474974513(

相关内容

最新更新