r - 将多个 csv 文件(类似列)与 r 中的选择性行和列合并为一个
问题描述
我有大约 300-500 个 CSV 文件,开头有一些字符信息,两列作为数字数据。我想用这样的方式制作一个包含所有数值的data.frame,这样我就有一次X列和多个Y,没有字符行。
**File1** has two-column and more than a thousand rows: an example looks like
info info
info info
info info
X Y
1 50.3
2 56.2
3 96.5
4 56.4
5 65.2
info 0
**File2**
info info
info info
info info
X Y
1 46.3
2 65.2
3 21.6
4 98.2
5 25.3
info 0
Only Y values are changing from file to file, I want to add all the files in one file with selective rows and make a data frame. Such as I want as a data frame.
X Y1 Y2
1 46.3 50.3
2 65.2 56.2
3 21.6 96.5
4 98.2 56.4
5 25.3 65.2
I tried
files <- list.files(pattern="*.csv")
l <- list()
for (i in 1:length(files)){
l[[i]] <- read.csv(files[i], skip = 3)
}
data.frame(l)
This gives me
X1 Y1 X2 Y2
1 46.3 1 50.3
2 65.2 2 56.2
3 21.6 3 96.5
4 98.2 4 56.4
5 25.3 5 65.2
info 0 info 0
如何仅将最后一行和 X 列作为第一列跳过(因为 X 值不会改变)
解决方案
定义一个Read
读取一个文件的函数,删除所有不以数字开头的行。我们sep=","
用来指定每个文件中的字段用逗号分隔。然后使用Read
withread.zoo
读取和合并给出 zoo object 的文件z
。最后,要么将其用作动物园对象,要么将其转换为数据框,如图所示。
library(zoo)
Read <- function(f) {
read.table(text = grep("^\\d", readLines(f), value = TRUE), sep = ".")
}
z <- read.zoo(Sys.glob("*.csv"), read = Read)
DF <- fortify.zoo(z)
推荐阅读
- machine-learning - DBSCAAN、OPTICS、KMEANS等聚类模型
- matlab - MatLab希望函数接受多个值并输出多个值
- wordpress - WordPress:是否可以在小部件激活时将小部件添加到页脚/侧边栏?
- python - 加入两个不同大小的列表以在 python 中创建一个新字典
- csv - Heroku 可以将文件保存到 Github 吗?
- python - 修复字符串中错误的分隔符
- mypy - 'None' 对象的 mypy pop 错误不可迭代
- flutter - Flutter:过滤器ListViewBuilder中的句柄值不存在
- html - 结合 overflow-y: scroll 和 overflow-x: visible
- vue.js - 全局 vue 对象未定义