Convert text file data into table in R

一笑奈何 提交于 2019-12-13 20:59:04

问题


I have data that has the form

sr:user1
target:user2
vt:4
time:12
sr:user3
target:user4
vt:42
time:120

Is there a simple way to make the data looks like the following by using R:

sr        target  vt  time
user1     user2    4   12
user3     user4    42  120

回答1:


Assume your data is in the file data.csv

require(data.table)
f <- fread("data.csv", header=FALSE)
(x <- unstack(f, V2 ~ V1) )



回答2:


This makes the assumption that your text file has a regular arrangement: scan can handle regular list input of multiple line data. Read the scan-help page section on the "what" argument for precise details.

inp <- scan(text= "sr:user1
 target:user2
 vt:4
 time:12
 sr:user3
 target:user4
 vt:42
 time:120", what=list(sr="",target="", vt="", time=""))
#Read 2 records
data.frame( lapply(inp, sub, patt=".*[:]", repl="") )
#---------------
     sr target vt time
1 user1  user2  4   12
2 user3  user4 42  120


来源:https://stackoverflow.com/questions/33585344/convert-text-file-data-into-table-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!