How to properly import a semicolon
I have been trying to import the following semi-colon separated file:
# word len;freq;mean;sens;npos;u;orthon;freqn;bgp WN000000
fiber "5;8.671;1;5;1;0;5;6.1;0;-1" 10000000
clad "4;6.78;2;2;1;1;8;7.84;2026;-1" 10000000
tucker "6;8.103;2;3;2;0.91829583405449;7;5.5;4547;-1" 10000000
I tried both read.csv
and data.table::fread
, but with no luck. read.csv
recognizes some of headers and the actual values are all under the first column:
X..word.len freq mean sens npos u orthon freqn bgp.WN000000
1 fibert5;8.671;1;5;1;0;5;6.1;0;-1t10000000 NA NA NA NA NA NA NA NA
2 cladt4;6.78;2;2;1;1;8;7.84;2026;-1t10000000 NA NA NA NA NA NA NA NA
3 tuckert6;8.103;2;3;2;0.91829583405449;7;5.5;4547;-1t10000000 NA NA NA NA NA NA NA NA
fread
recognizes the first column, but merges all the others into one.
X..word len.freq.mean.sens.npos.u.orthon.freqn.bgp WN000000
1 fiber 5;8.671;1;5;1;0;5;6.1;0;-1 10000000
2 clad 4;6.78;2;2;1;1;8;7.84;2026;-1 10000000
3 tucker 6;8.103;2;3;2;0.91829583405449;7;5.5;4547;-1 10000000
Can anyone help out?
Here is what I try (and edited based on David Arenburg 's comment).
Read and process the header line first; then read the remaining lines while skipping the first line:
library(data.table)
header <- strsplit(readLines('test.txt', n = 1), 's+')[[1]][-1]
res <- fread('test.txt', skip = 1, header = FALSE)
setnames(res, 1:3, header)
res[, strsplit(header[2], ';')[[1]] :=
tstrsplit(get(header[2]), ';', type.convert = TRUE, fixed = TRUE)[-10]]
res[, header[2] := NULL]
# word WN000000 len freq mean sens npos u orthon freqn bgp
# 1: fiber 10000000 5 8.671 1 5 1 0.0000000 5 6.10 0
# 2: clad 10000000 4 6.780 2 2 1 1.0000000 8 7.84 2026
# 3: tucker 10000000 6 8.103 2 3 2 0.9182958 7 5.50 4547
It should be noted that there are 9 items seperated by ;
in second column of the input file, but the following rows have 10 ;
-seperated items.
As far as I can tell, you've basically got two separators working there. It might be worth handling this manually, rather than using a standard reading function.
Read the file in, get rid of the quotations, then separate by both space and semicolon delimiters.
library( magrittr )
input <- readLines( "~/Desktop/Untitled" ) %>%
gsub( '"|^# +', "", . ) %>%
strsplit( " +|;" )
Convert everything except the first row to a data frame.
input[-1] %>%
do.call( what = rbind ) %>%
as.data.frame()
Then use the first row as column names. We need to add an extra here, since your header doesn't have enough names to cover your data.
names( df ) <- c( input[[1]][1:10], "fill.col", input[[1]][11] )
Result:
> df
word len freq mean sens npos u orthon freqn bgp fill.col WN000000
1 fiber 5 8.671 1 5 1 0 5 6.1 0 -1 10000000
2 clad 4 6.78 2 2 1 1 8 7.84 2026 -1 10000000
3 tucker 6 8.103 2 3 2 0.91829583405449 7 5.5 4547 -1 10000000
链接地址: http://www.djcxy.com/p/96270.html
上一篇: JSlint错误'不要在循环中创建函数。' leads to question about Javascript
下一篇: 如何正确导入分号