以矩阵读入r而不分割 [英] read in matrix into r without delimination
本文介绍了以矩阵读入r而不分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读入R的文件看起来就是这个
a file I want to read into R looks liek this
0010101010101010101
1110101010101010101
1111110101010111000
0001010101000010100
当我读到这个问题是,R认为每一行都是一个数字,只显示
when I read that in the problem is that R thinks every row is a number and just shows
V1
1 Inf
2 Inf
3 Inf
4 Inf
5 Inf
6 Inf
我如何读取它矩阵与0和其他元素?
how can I read it in as a matrix with 0 and the other element?
推荐答案
一个选项是
as.matrix(read.fwf('triub.txt', widths=rep(1,19)))
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
#[1,] 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[2,] 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[3,] 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 0
#[4,] 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0
或
as.matrix(read.table(text=gsub("", ' ', readLines('triub.txt'))))
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
#[1,] 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[2,] 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[3,] 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 0
#[4,] 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0
或者您可以管道
与 sed
或 awk
( linux
)
as.matrix(read.table(pipe("sed 's/./& /g' triub.txt"), header=FALSE))
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
#[1,] 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[2,] 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
#[3,] 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 0 0 0
#[4,] 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0
as.matrix(read.table(pipe("awk 'BEGIN{FS=\"\"; OFS=\" \"}{$1=$1}1' triub.txt"),
header=FALSE))
这篇关于以矩阵读入r而不分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文