在R中将数字字符串转换为数字数据类型

时间:2015-10-26 10:44:50

标签: r

我有一个10x1的字符矩阵(例如e212m)。

> print(e212m)
      [,1]                          
  [1,] "0000000000000111111000000000"
  [2,] "0000000000000111111100000000"
  [3,] "0000000000001111111100000000"
  [4,] "0000000000001111111100000000"
  [5,] "0000000000011100111100000000"
  [6,] "0000000000011111111100000000"
  [7,] "0000000000011111111100000000"
  [8,] "0000000000011111111100000000"
  [9,] "0000000000001111111000000000"
  [10,] "0000000000000011111000000000"
  > dim(e212m)
  [1] 10  1
  > typeof(e212m)
  [1] "character"

我想将任何行的每个字符转换为整数。但不喜欢

"0000000000000111111000000000"(string/character) to integer = 0000000000000111111000000000

我想要将每个角色更改为digit.eg

"0" "0" "1" "1" to number 0 0 1 1.

这样我最终可以获得10x29的整数矩阵。 P.S:我是R的新手。欢迎直接命令执行上述任务。

3 个答案:

答案 0 :(得分:3)

x<-"0000000000000111111000000000"
y<-as.numeric(strsplit(x,split='')[[1]])

将返回

y
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0

如果矩阵命名为m,请使用:

m2<-apply(m,1,function(x){as.numeric(strsplit(x,split='')[[1]])})
m2<-t(m2)

答案 1 :(得分:2)

x <- c("0000000000000111111000000000", "0000000000000111111100000000", "0000000000001111111100000000")
y <- paste(x, collapse = "\n")
read.fwf(textConnection(y), rep(1, nchar(x[1])))
#  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28
#1  0  0  0  0  0  0  0  0  0   0   0   0   0   1   1   1   1   1   1   0   0   0   0   0   0   0   0   0
#2  0  0  0  0  0  0  0  0  0   0   0   0   0   1   1   1   1   1   1   1   0   0   0   0   0   0   0   0
#3  0  0  0  0  0  0  0  0  0   0   0   0   1   1   1   1   1   1   1   1   0   0   0   0   0   0   0   0

答案 2 :(得分:0)

尝试使用正则表达式。

gsub('(\\d)','\\1 ',x)

gsub('(?<=\\d)(\\d)',' \\1',x,perl=T)