gpt4 book ai didi

r - 使用文件名命名列

转载 作者:行者123 更新时间:2023-12-02 21:56:50 24 4
gpt4 key购买 nike

我有数百个 csv 文件(R 中的动物园对象),有 2 列:

"Index","pp"<br/>
1951-01-01,22.9<br/>
1951-01-02,4.3<br/>
1951-01-03,4.6

我希望第二列包含每个文件的名称。例如,当文件名是02O_zoo.csv时我希望第二列是“02O”而不是“pp”。有没有自动执行此操作的方法?

谢谢

最佳答案

(1) 来自文件 read.zoo可以将文件名的字符向量作为其第一个参数,因此:

# create test files
Lines <- '"Index","pp"
1951-01-01,22.9
1951-01-02,4.3
1951-01-03,4.6'
cat(Lines, file = "testzoo01.csv")
cat(Lines, file = "testzoo02.csv")

# read.zoo reads the files named in Filenames and merges them
library(zoo)
Filenames <- dir(pattern = "testzoo.*csv")

z <- read.zoo(Filenames, sep = ",", header = TRUE)

给出了这个:

> z
testzoo01.csv testzoo02.csv
1951-01-01 22.9 22.9
1951-01-02 4.3 4.3
1951-01-03 4.6 4.6

如果需要,可以通过将名称放在 Filenames 上来进一步修改名称。变量,例如names(Filenames) <- gsub("testzoo|.csv", "", Filenames) ,或者通过修改结果的名称,例如names(z) <- gsub("testzoo|.csv", "", names(z))

(2) 来自动物园对象。如果之前已读过它们,请尝试以下操作:

# create test objects using Lines and library() statement from above
testobj1 <- testobj2 <- read.zoo(textConnection(Lines), header = TRUE, sep = ",")

# merge them into a single zoo object
zz <- do.call(merge, sapply(ls(pattern = "testobj.*"), get, simplify = FALSE))

给出了这个:

> zz
testobj1 testobj2
1951-01-01 22.9 22.9
1951-01-02 4.3 4.3
1951-01-03 4.6 4.6

zz的名字可以按照上面的讨论进一步修改。

关于r - 使用文件名命名列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com