Thursday, August 11, 2022

[FIXED] How to substitute non-binary (other than 0/1) characters in a numeric vector with zeros (in R)?

Issue

When creating a complex funtion, I needed to convert all non-binary (other than 0/1) characters in a numeric vector to zeros:

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

How to convert
c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 7, 4, 9, 7, 4, 5)
to
c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)?


Solution

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


Answered By - liuminzhao
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.