0

My list consist values as shown.

Mylist:
[[1]]
[1] 1 1 1 0 1 1

[[2]]
[1] 0 0 0 0 1 0

[[3]]
[1] 0 0 0 0 1 0

I need to convert this binary values to decimal. I am using BinToDec() function. But here values are space separated. How to get the values like 111011, 000010 etc in that list. I have tried with gsub, but it removes spaces in string. Thanks!

9113303
  • 852
  • 1
  • 16
  • 30

3 Answers3

2

Try using gsub with lapply to remove all whitespace:

BinToDec <- function(x) 
    sum(2^(which(rev(unlist(strsplit(as.character(x), "")) == 1))-1))

lst <- list("1 1 1 0 1 1", "0 0 0 0 1 0", "0 0 0 0 1 0")
unlist(lapply(lst, function(x) BinToDec(gsub("\\s+", "", x))))

[1] 59  2  2

I took the above BinToDec function from this SO answer, which maybe is also where you saw it.

Edit:

If you actually have a list of integer vectors, then use this option:

lst <- list(c(1,1,1,0,1,1), c(0,0,0,0,1,0), c(0,0,0,0,1,0))
unlist(lapply(lst, function(x) BinToDec(paste(as.character(x), collapse=""))))

[1] 59  2  2

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • It works for the conversion, But here `lst <- list("1 1 1 0 1 1", "0 0 0 0 1 0", "0 0 0 0 1 0")` is given manually. The list 'Mylist' directly taken to this. So i tried `as.character` conversion. it converts like this. ( "1" "1" "1" "0" "1" "1" ). So that i am getting decimal values like `4472900 64 64` . This is not the expeccted one. – 9113303 Oct 12 '18 at 09:40
  • @9113303 Why are you using `as.character`? I don't understand your comment. Do you have a list of factors? – Tim Biegeleisen Oct 12 '18 at 09:42
  • @TimBiegeleisen I think it's a list of integer vectors and OP is saying it's space separated because that's what it looks like when you print it. – duckmayr Oct 12 '18 at 10:01
  • 1
    @duckmayr I added a solution in case you are right. – Tim Biegeleisen Oct 12 '18 at 10:16
0

Thanks.as.numeric(paste(as.character(Mylist[[i]]),collapse = "")) solves the issue.

9113303
  • 852
  • 1
  • 16
  • 30
0

Package (StringR)

The code below allows to find certain character and remove or replace

Code str_replace_all(x, " ", "")

related to you

str_replace_all(list, " ", "")

Explanation

str_replace_all(Dataset, "character you are looking up ", "replacement character ")

If only for a certain row be sure to do the following

str_replace_all(Dataset$Row, "character you are looking up ", "replacement character ")