我想使用fread
仅拉入名称与条件匹配的列。 (在这种情况下,我想拉入所有包含标签email
的列。)假设您在工作目录中的tempdata.txt
文件中拥有此数据:
col1,col2,col3,email1,email2,col4,url1,url2,col5
1,2,3,4,5,6,7,8,9
9,8,7,6,5,4,3,2,1
x,x,x,[email protected],[email protected],y,y,y,y
a,a,a,a,a,a,http://google.com,http://stackoverflow.com,a
如果知道名称,可以使用fread
加载列的子集:
test <- data.table::fread("tempdata.txt", select=c("email1","email2"))
> test
email1 email2
1: 4 5
2: 6 5
3: [email protected] [email protected]
4: a a
是否还可以使用字符串匹配进行选择?我正在尝试模仿这种行为,但是在fread
命令中:
> all <- data.table::fread("tempdata.txt")
> all %>% select(contains("email"))
email1 email2
1: 4 5
2: 6 5
3: [email protected] [email protected]
4: a a
感谢您的见解。
我不知道fread
不具有该功能(尽管我在文档中没有看到它)。但是,相对便宜的方法是读取第一两行,获取列名,grep
,然后从那里继续。]
library(data.table)
fwrite(data.table(a=1:2, email1=c('a','b'), snailmail=c('c','d'), email2=c('e','f')), "test.csv")
fread("test.csv", nrows=1)
# a email1 snailmail email2
# 1: 1 a c e
cols <- colnames(fread("test.csv", nrows=0))
cols
# [1] "a" "email1" "snailmail" "email2"
fread("test.csv", select = grep("^email", cols, value = TRUE))
# email1 email2
# 1: a e
# 2: b f