myColumns = csv[,c("a1", "a2", "a3")]
获取那些列.如果要选择以"a" 开头的所有列(编辑):
csv[,grep("^a", names(myColumns))]
如果要直接从csv文件中将选定列读入R而不读取整个文件,可以尝试使用此方法fread()
.
library(data.table) fread(file, select = grep("^a", names(fread(file, nrow = 0L))))
这只读取文件的第一行(标题),然后用于grep()
确定以值开头的值的a
位置.然后我们在列选择参数中使用该结果select
来获取我们想要的列.
让我们尝试一下mtcars
,只查找以开头的列d
.
## write mtcars to file write.csv(mtcars, row.names = FALSE, quote = FALSE, file = "mtcars.csv") ## now read only the columns beginning with 'd' DT <- fread("mtcars.csv", select = grep("^d", names(fread("mtcars.csv", nrow = 0L)))) ## have a look head(DT) # disp drat # 1: 160 3.90 # 2: 160 3.90 # 3: 108 3.85 # 4: 258 3.08 # 5: 360 3.15 # 6: 225 2.76