我想上传一个包含多个头行和空格的数据文件到R.我已经复制了这里的数据
# File name
#
#@ 1 "Some text" "aa"
#@ 2 "Some text" "bb"
#@ 3 "Some text" "cc"
#@ 4 "Some text" "dd"
#@ 5 "Some text" "ee"
#@ 6 "Some text" "ff"
#
#
#
#
0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00
1.000000e-03 3.727051e-04 2.532203e-04 4.736003e-04 3.727051e-07 0.000000e+00
2.000000e-03 2.266785e-03 1.540081e-03 2.880429e-03 2.639490e-06 0.000000e+00
3.000000e-03 7.538553e-03 5.121786e-03 9.579321e-03 1.017804e-05 0.000000e+00
4.000000e-03 1.838835e-02 1.249329e-02 2.336627e-02 2.856639e-05 0.000000e+00
5.000000e-03 3.703296e-02 2.516073e-02 4.705817e-02 6.559935e-05 0.000000e+00
6.000000e-03 2.266785e-03 1.540081e-03 2.880429e-03 2.639490e-06 0.000000e+00
7.000000e-03 7.538553e-03 5.121786e-03 9.579321e-03 1.017804e-05 0.000000e+00
8.000000e-03 1.838835e-02 1.249329e-02 2.336627e-02 2.856639e-05 0.000000e+00
9.000000e-03 3.703296e-02 2.516073e-02 4.705817e-02 6.559935e-05 0.000000e+00
可以看到,它包含9行和6列。问题是在包含列名的实际数据集之上有一堆标题数据。我尝试使用read_table命令和空白分隔符,但是列被限制为3,而不是6
dat <- read_table("example.txt", col_names = F)
我想导入数据,转换为数字和标签与文件中列出的标题名称的每一列。所以第一列的名称是&;Some text &;,第二列的名称是&;Some text bb&;等等......有办法得到这个吗?我有100个这样的文件,并希望自动化这个过程
如果文件是quux.txt
,则
dat <- read.table("quux.txt", skip = 13, header = FALSE)
dat
# V1 V2 V3 V4 V5 V6
# 1 0.000 0.0000000000 0.0000000000 0.0000000000 0.000000e+00 0
# 2 0.001 0.0003727051 0.0002532203 0.0004736003 3.727051e-07 0
# 3 0.002 0.0022667850 0.0015400810 0.0028804290 2.639490e-06 0
# 4 0.003 0.0075385530 0.0051217860 0.0095793210 1.017804e-05 0
# 5 0.004 0.0183883500 0.0124932900 0.0233662700 2.856639e-05 0
# 6 0.005 0.0370329600 0.0251607300 0.0470581700 6.559935e-05 0
从这里,您可以使用
提取列名nms <- readLines(pipe("grep '^#@' quux.txt")) |>
sub(pattern = '.*"(\S+)"\s*$', replacement = '\1')
nms
# [1] "aa" "bb" "cc" "dd" "ee" "ff"
names(dat) <- nms
dat
# aa bb cc dd ee ff
# 1 0.000 0.0000000000 0.0000000000 0.0000000000 0.000000e+00 0
# 2 0.001 0.0003727051 0.0002532203 0.0004736003 3.727051e-07 0
# 3 0.002 0.0022667850 0.0015400810 0.0028804290 2.639490e-06 0
# 4 0.003 0.0075385530 0.0051217860 0.0095793210 1.017804e-05 0
# 5 0.004 0.0183883500 0.0124932900 0.0233662700 2.856639e-05 0
# 6 0.005 0.0370329600 0.0251607300 0.0470581700 6.559935e-05 0