从R中的多个文本文件中提取第一行
extracting first line from multiple text files in R
我想从文本文件中提取单行,并根据 "id" 的变化将它们放入新的 table。
例如,我希望第 1,53 行和第 87 行与我的新 table 分开
我的文件太多了,手动操作会很费时间。
有没有办法使用 R 来做到这一点?
"row.name" "date" "latitude" "longitude" "depth" "id"
"1" "2014-12-10 17:37:23" -38.6219483442355 142.930328034342 0 "0005"
"2" "2014-12-10 17:37:27" -38.6219774268193 142.930269244481 0 "0005"
...
"53" "2014-12-10 17:37:31" -38.6220065094031 142.93021045462 0 "0009"
"54" "2014-12-10 17:37:35" -38.6220355919869 142.930151664759 0 "0009"
"55" "2014-12-10 17:37:39" -38.6220646745707 142.930092874898 0.61"0009"
...
"87" "2014-12-10 17:37:47" -38.6221228397384 142.929975295176 0 "0018"
"89" "2014-12-10 17:37:51" -38.6221519223222 142.929916505315 0 "0018"
对于您的数据框,您可以使用 dplyr
按 id 分组,然后作为 summarise
函数,调用 head
并使其 select 只有第一行(而不是默认的 6)。这是一个玩具示例。
df <- data.frame(id = c("0005", "0005", "0009", "0009", "0009"), content = c(1:5))
df$id <- as.factor(df$id)
df %>% group_by(id) %>% summarise(single = head(content, 1))
Source: local data frame [2 x 2]
id single
1 0005 1
2 0009 3
我想从文本文件中提取单行,并根据 "id" 的变化将它们放入新的 table。
例如,我希望第 1,53 行和第 87 行与我的新 table 分开 我的文件太多了,手动操作会很费时间。
有没有办法使用 R 来做到这一点?
"row.name" "date" "latitude" "longitude" "depth" "id"
"1" "2014-12-10 17:37:23" -38.6219483442355 142.930328034342 0 "0005"
"2" "2014-12-10 17:37:27" -38.6219774268193 142.930269244481 0 "0005"
...
"53" "2014-12-10 17:37:31" -38.6220065094031 142.93021045462 0 "0009"
"54" "2014-12-10 17:37:35" -38.6220355919869 142.930151664759 0 "0009"
"55" "2014-12-10 17:37:39" -38.6220646745707 142.930092874898 0.61"0009"
...
"87" "2014-12-10 17:37:47" -38.6221228397384 142.929975295176 0 "0018"
"89" "2014-12-10 17:37:51" -38.6221519223222 142.929916505315 0 "0018"
对于您的数据框,您可以使用 dplyr
按 id 分组,然后作为 summarise
函数,调用 head
并使其 select 只有第一行(而不是默认的 6)。这是一个玩具示例。
df <- data.frame(id = c("0005", "0005", "0009", "0009", "0009"), content = c(1:5))
df$id <- as.factor(df$id)
df %>% group_by(id) %>% summarise(single = head(content, 1))
Source: local data frame [2 x 2]
id single
1 0005 1
2 0009 3