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
  • 772
  • 11
  • 28

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
  • 451,927
  • 24
  • 239
  • 318
0

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

9113303
  • 772
  • 11
  • 28
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 ")