Using a file name to indicate a column

I have hundreds of csv files (zoo objects in R) with two columns:

"Index","pp"
1951-01-01,22.9
1951-01-02,4.3
1951-01-03,4.6

I want the second column to have the name of each file. For example, when the file name is 02O_zoo.csv , I would like the second column to be "02O" instead of "pp". Is there an automatic way to do this?

thanks

+6
source share
1 answer

(1) From read.zoo files, read.zoo can take a character vector of file names as its first argument, therefore:

 # 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) 

which gives the following:

 > 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 

One could, if necessary, change the names by putting the names in the Filenames variable, for example. names(Filenames) <- gsub("testzoo|.csv", "", Filenames) or by changing the names of the result, for example. names(z) <- gsub("testzoo|.csv", "", names(z))

(2) From the objects of the zoo . If you have read them before, try the following:

 # 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)) 

which gives the following:

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

The zz names can be changed further, as in the discussion above.

+8
source

Source: https://habr.com/ru/post/896415/


All Articles