如何解决努力使用read_tsv代替read.csv
回答:非常感谢Bob,ffs问题没有指定comment ='#'。当“跳过”应该跳过违规行时,为什么这样做仍然是一个谜。另请参阅Gray的注释:针对非R解决方案的Excel的“文本到列”功能。
伙计们,
多年来,这一直是我的恶魔。
我使用的数据始终是制表符分隔的.txt文件的集合,因此我的分析总是从收集每个文件的文件路径并将它们输入到read.csv()并绑定到df上开始。
dat <- list.files(
path = 'data',pattern = '*.txt',full.names = TRUE,recursive = TRUE
) %>%
map_df( ~read.csv( .,sep='\t',skip=16) ) # actual data begins at line 16
这正是我想要的,但是最近几年我一直在过渡到tidyverse。
我不介意使用utils :: read.csv(),在我的数据集通常很小的情况下,不会感觉到readr的速度优势。但是,为了保持一致性,我宁愿使用readr。
当我做同样的事情时,但是sub readr :: read_tsv(),即
dat <-
.... same call to list.files()
%>%
map_df( ~read_tsv( .,skip=16 ))
我总是得到一个空(0x0)表。但这似乎是在“读取”数据,因为我为数据中的每一列都从“使用列规范分析:cols()”得到了警告打印。
很显然,我在这里误会了,但是我不知道我不了解什么,这使我寻找具有挑战性和徒劳的答案。
那么...我在这里做错什么了吗?
谢谢!
编辑:我的数据文件(其中一个)的示例代码段已被请求,希望此格式格式正确!
# KLIBS INFO
# > KLibs Commit: 11a7f8331ba14052bba91009694f06ae9e1cdd3d
#
# EXPERIMENT SETTINGS
# > Trials Per Block: 72
# > Blocks Per Experiment: 8
#
# SYSTEM INFO
# > Operating System: macOS 10.13.4
# > Python Version: 2.7.15
#
# DISPLAY INFO
# > Screen Size: 21.5" diagonal
# > Resolution: 1920x1080 @ 60Hz
# > View Distance: 57 cm
PID search_type stimulus_type present_absent response rt error
3 time COLOUR present absent 5457.863881 TRUE
3 time COLOUR absent absent 5357.009108 FALSE
3 time COLOUR present present 2870.76412 FALSE
3 time COLOUR absent absent 5391.404728 FALSE
3 time COLOUR present present 2686.6131 FALSE
3 time COLOUR absent absent 5306.652878 FALSE
编辑:使用Jukob的建议
files <- list.files(
path = 'data',recursive = TRUE
)
for (i in 1:length(files)) {
print(read_tsv(files[i],skip=16))
}
打印:
Parsed with column specification:
cols()
# A tibble: 0 x 0
... for each file
如果我打印文件,则可以得到正确的文件路径列表。如果删除skip = 16,我得到:
Parsed with column specification:
cols(
`# KLIBS INFO` = col_character()
)
Warning: 617 parsing failures.
row col expected actual file
15 -- 1 columns 21 columns 'data/raw/2019/colour/p1.2019-02-28.txt'
16 -- 1 columns 21 columns 'data/raw/2019/colour/p1.2019-02-28.txt'
17 -- 1 columns 21 columns 'data/raw/2019/colour/p1.2019-02-28.txt'
18 -- 1 columns 21 columns 'data/raw/2019/colour/p1.2019-02-28.txt'
19 -- 1 columns 21 columns 'data/raw/2019/colour/p1.2019-02-28.txt'
... ... ......... .......... ........................................
See problems(...) for more details.
... for each file
解决方法
您可以尝试遵循以下代码吗? i的值可能会让您知道哪个文件有问题。
files <- list.files(path = "path",full.names = T,pattern = ".csv")
for (i in 1:length(files)){
print(read_tsv(files[i],skip = 16))
}
,
FWIW通过以下代码,我可以使用您的代码段解决问题:
# Didn't work for me since when I copy and paste your snippet,# the tabs become spaces,but I think in your original file
# the tabs are preserved so this should work for you
read_tsv("dat.tsv",comment = "#")
# This works for my case
read_table2("dat.tsv",comment = "#")
甚至不需要指定skip
参数!
但是,也不知道为什么使用skip
而不是comment
会失败...:(