简体   繁体   English

如何将无空间数据转换为R中定界的制表符?

[英]How to convert a spaceless data into tab delimited in R?

I have a data set in form of:(this is just an example) 我有以下形式的数据集:(这只是一个示例)

1324501020
3241030205
4332020134

which each row represents responses of an examinee to a set of items on a test. 每行代表考生对测试中一组项目的回答。 The data are stored in a text file (eg data.txt) but I need to convert them into a matrix format such that each number be place in a cell, like this: 数据存储在文本文件(例如data.txt)中,但是我需要将它们转换为矩阵格式,以便将每个数字放置在单元格中,如下所示:

1 3 2 4 5 0 1 0 2 0
3 2 4 1 0 3 0 2 0 5
4 3 3 2 0 2 0 1 3 4

in other words, the final data set supposed to be a matrix of numbers in which columns contain responses to each item and rows are examinees. 换句话说,最终的数据集应该是一个数字矩阵,其中的列包含对每个项目的响应,行是被检查者。 Any idea?? 任何想法??

x <- read.fwf(file = "c:\\whatever\\data.txt", width=c(1,1,1,1,1,1,1,1,1,1))

噢,祝StackOverflow旅途愉快!

If the data is in a text file and the file contains only data like shown, then the best approach is probably the read.fwf approach as described by @Penguin_Knight. 如果数据在文本文件中,并且文件仅包含如图所示的数据,则最好的方法可能是@Penguin_Knight描述的read.fwf方法。 But if there are additional data fields in the file that don't fit the fixed width format, or if the data has been copied or grabbed in a different way so that it is already in a character vector in R, then here are some other options. 但是,如果文件中还有其他数据字段不适合固定宽度格式,或者如果数据已经以其他方式复制或抓取以致于它已经在R中的字符向量中,那么这里还有一些其他内容选项。

You can still use the read.fwf approach with a textConnection . 您仍然可以将read.fwf方法与textConnection一起使用。

You can use the strsplit function to split the strings into the individual digits and use as.numeric to convert them to numbers. 您可以使用strsplit函数将字符串拆分为单个数字,并使用as.numeric将其转换为数字。

You can use the strapply function from the gsubfn package to match individual digits and extract them (and pass to as.numeric again). 您可以使用gsubfn包中的strapply函数来匹配各个数字并提取它们(然后再次传递给as.numeric )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM