从具有可变字段数的 CSV 导入前三个和后三个字段

Importing first three and last three fields from CSV with variable number of fields

我有一个 csv 格式的数据集。不幸的是,每一行都有不同数量的“,”逗号。我有兴趣从 R 中的文件中导入前 3 个和后 3 个变量。

例如:

> line: "A","B","C","D",...,"X",Y","Z"

我想实现以下`

> line: "A","B","C","X","Y","Z"

我尝试使用 grep,找到 - 通过使用正则表达式 - 前 3 个变量:

new_data <- grep("([^,]+)(,[^,]+){2}", dataset, values=TRUE)

在该操作之后,它向我显示了存在该表达式的所有行。

如何使用 grep 删除行中的以下变量,如果可能的话,如何删除整个间隔(<3;n-3> 中的每个变量)。

你现在有其他方法解决这个问题吗?

试试 awk-

awk -F, '{print , , , $(NF-2), $(NF-1), $(NF)}' file

-F, 将字段分隔符更改为逗号。

NF 是数据集中的最后一个字段。 NF-1NF-2 很明显。

我做了一个示例文件-

$cat file.csv
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z 
a, b, c, d, e, f, g, h, i
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v

正在做-

$awk -F, '{print , , , $(NF-2), $(NF-1), $(NF)}' file.csv

输出-

a  b  c  x  y  z 
a  b  c  g  h  i
a  b  c  t  u  v

编辑

如果您执行以下操作,此解决方案将非常有效-

> system('awk -F, \'{print , , , $(NF-2), $(NF-1), $(NF)}\' file.csv')

其中 file.csv 是包含数据的文件。

命令行解决方案会更容易,但如果您想要在 R 内部解决方案,在 R 代码中,则通过 textConnection 过滤传入的 CSV,并使用字符串操作或正则表达式提取第一个和最后三个字段:

csvConn <- textConnection('your.csv')
<use string operations or regex to extract the first and last three fields>
read.csv(data = csvFixed, ...)

这行得通,我以前做过。 请参阅涉及 textConnection and read.csv(data=...) 的其他类似解决方案。不过我找不到一个非常干净的例子。

使用applyheadtail的组合:

d2 <- data.frame(t(apply(d1, 1, function(x) c(head(x[x != ''],3), tail(x[x != ''],3)))))

导致:

> d2
  X1 X2 X3 X4 X5 X6
1  a  b  c  x  y  z
2  a  b  c  g  h  i
3  a  b  c  t  u  v

使用@VarunM的数据:

d1 <- read.csv(text='a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
a, b, c, d, e, f, g, h, i
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v', header = FALSE, fill = TRUE)