[英]is there a way to convert a string with numbers to a list of numeric values in R?
[英]Convert string of numbers into numeric data type in 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的整數矩陣。 PS:我是R的新手。歡迎執行上述任務的直接命令。
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)
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
嘗試使用正則表達式。
gsub('(\\d)','\\1 ',x)
要么
gsub('(?<=\\d)(\\d)',' \\1',x,perl=T)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.