r - 只读取选定的列

标签 r import r-faq

谁能告诉我如何只读取下面每年数据的前 6 个月(7 列),例如使用 read.table()

Year   Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec   
2009   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25
2010   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25 
2011   -21  -27   -2   -6  -10  -32  -13  -12  -27  -30  -38  -29

最佳答案

假设数据在文件 data.txt 中,您可以使用 read.table()colClasses 参数来跳过列。这里前 7 列的数据是 "integer",我们将剩下的 6 列设置为 "NULL" 表示应该跳过它们

> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 
+            header = TRUE)
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

根据实际数据类型,将 “integer” 更改为 ?read.table 中详述的可接受类型之一。

data.txt 看起来像这样:

$ cat data.txt 
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29

并且是通过使用创建的

write.table(dat, file = "data.txt", row.names = FALSE)

dat 在哪里

dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L, 
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L, 
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L, 
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))

如果事先不知道列数,实用函数 count.fields 将通读文件并计算每行中的字段数。

## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))

关于r - 只读取选定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43901143/

相关文章:

r - 编织时将消息打印到 R markdown 控制台

php - 将csv文件导入mysql并同时更改日期时间格式

python - 如何将 python 脚本分成几部分并循环导入这些部分?

r - 如何连接(合并)数据框(内部、外部、左、右)

r - 为什么这些数字不相等?

r - 如何 group_by 多个灵活的标准

r - 时间戳差异

r - download.file() 在 Windows 上生成 "invalid"zip 文件,但在 Mac 上工作正常

python-3.x - 递归导入所有文件夹中的所有 .py 文件

r - 具有 (1) ALL 和 (2) ANY 列大于特定值的子集行