问题
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