【问题标题】:Combine multiple csv files (similar column) in one with selective row and column in r将多个 csv 文件(相似列)与 r 中的选择性行和列合并为一个
【发布时间】:2020-04-07 09:42:54
【问题描述】:

我有大约 300-500 个 CSV 文件,开头有一些字符信息,两列作为数字数据。我想用这样的方式制作一个包含所有数值的数据框

**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 值不会改变)

【问题讨论】:

    标签: r loops csv


    【解决方案1】:

    定义一个函数Read,它读取一个文件,删除所有不以数字开头的行。我们使用sep="," 指定每个文件中的字段以逗号分隔。然后使用Readread.zoo 来读取和合并给出动物园对象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)
    

    【讨论】:

    • 感谢您的回答。我将 X 和 Y 作为非数字的列标题。
    • 对,但您不需要它们。反正它们都是一样的。显示的代码将按文件名标记每一列。
    猜你喜欢
    • 2016-03-25
    • 2013-07-14
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多