PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

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

 August 11, 2022     binary, decimal, r, replace     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing