Ringo145
Ringo145

Reputation: 7

How to convert a two column csv into a vector of the second column?

> temp = list.files(pattern="*.csv")
> myfiles = lapply(temp, read.csv)

I am using the above code to read in multiple csv-files. The result being that each cvs-file read in the following form:

> myfiles
[[1]]
         Date   Payment
1  19/10/2003 -13275.00
2  19/11/2003    940.49
3  19/12/2003    884.71
4  19/01/2004    832.11
5  19/02/2004    782.49
6  19/03/2004    735.74
7  19/04/2004    691.64
8  19/05/2004    650.09
9  19/06/2004    610.91
10 19/07/2004    573.99
11 19/08/2004    539.20
12 19/09/2004    506.42
13 19/10/2004    475.54
14 19/11/2004    441.05
15 19/12/2004    413.91
16 19/01/2005    388.37
17 19/02/2005    364.31
18 19/03/2005    341.66
19 19/04/2005    320.34
20 19/05/2005    300.28
21 19/06/2005    281.39
22 19/07/2005    263.63
23 19/08/2005    246.91
24 19/09/2005    231.20
25 19/10/2005    216.41
26 19/11/2005    202.51
27 19/12/2005    189.43
28 19/01/2006    177.15
29 19/02/2006    165.60
30 19/03/2006    154.75
31 19/04/2006    144.55
32 19/05/2006    134.98
33 19/06/2006    125.99
34 19/07/2006    117.55
35 19/08/2006    109.62
36 19/09/2006    102.18

However i need to read the csv-files in this form:


> read.csv("cashflows1.csv", skip=1, header=F)$V2


[1] -13275.00    940.49    884.71    832.11    782.49    735.74    691.64    650.09    610.91    573.99    539.20
[12]    506.42    475.54    441.05    413.91    388.37    364.31    341.66    320.34    300.28    281.39    263.63
[23]    246.91    231.20    216.41    202.51    189.43    177.15    165.60    154.75    144.55    134.98    125.99
[34]    117.55    109.62    102.18


Is there a way for me to change "> myfiles = lapply(temp, read.csv)" such that it reads all csv-files in the required format (a vector of the second column which is titled "payments").

Upvotes: 0

Views: 239

Answers (2)

akrun
akrun

Reputation: 887911

We can use map

library(purrr)
unlist(map(myfiles, pluck, 'Payment'))

Also, we can use fread with select to read only the selected columns

library(data.table)
unlist(lapply(temp, fread, select = "Payment"))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389295

After reading the files in myfiles you could subset the 2nd column and convert it into a vector

c(sapply(myfiles, `[[`, 2))

Or using name of the column

c(sapply(myfiles, `[[`, "Payment"))

Upvotes: 1

Related Questions