Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the file name to name a column

Tags:

r

filenames

zoo

I have hundreds of csv files (zoo objects in R) with 2 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 a filename is 02O_zoo.csv I would like the second column to be "02O" instead of "pp". Is there an automatic way of doing this?

Thanks

like image 640
sbg Avatar asked Sep 01 '11 14:09

sbg


People also ask

What is a file name example?

A file name is the complete title of a file and file extension. For example, "readme. txt" is a complete file name. A file name may also describe only the first portion of the file.

How do I create a .name file?

Using File Explorer, right-click a file, and then select Rename. Type a new name for the document, and then press Enter.

What is column name?

In the context of a function, a GROUP BY clause, an ORDER BY clause, an expression, or a search condition, a column name refers to values of a column in some target table or view in a DELETE or UPDATE statement or table-reference in a FROM clause.


1 Answers

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

# 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 this:

> 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

It would be possible to modify the names further if desired by placing names on the Filenames variable, e.g. names(Filenames) <- gsub("testzoo|.csv", "", Filenames), or by modifying the names of the result, e.g. names(z) <- gsub("testzoo|.csv", "", names(z))

(2) From zoo Objects. If they have been read in previously then try this:

# 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 this:

> 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 names of zz could be modified further as in the discussion above.

like image 111
G. Grothendieck Avatar answered Oct 20 '22 11:10

G. Grothendieck