Reputation: 1255
I have some files like
myfiles <- c("1850-12.dat", "1851-10.dat", "1851-11.dat", "1851-1.dat", "1851-6.dat",
"1851-7.dat", "1851-8.dat", "1852-10.dat", "1852-11.dat", "1852-12.dat",
"1852-1.dat", "1852-2.dat", "1852-3.dat", "1852-4.dat", "1852-7.dat",
"1852-8.dat", "1852-9.dat", "1853-10.dat", "1853-11.dat", "1853-12.dat")
where the first number is the year and the second one is the month and I put them in a list with
myfilesContent <- lapply(myfiles, read.table, quote="\"")
I renamed the names of each element with
myfilesContent <- setNames(myfilesContent,myfiles)
>myfilesContent[1]
$`1850-12.dat`
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
.
.
.
What I would like to do is then to reorder the list elements according to the year and month information.
What I have done is to rename them with a value of the days since year, so the names of each list element look like
> names(myfilesContent)
[1] "335" "639" "670" "366" "517" "547" "578" "1005" "1036"
[10] "1066" "731" "762" "791" "822" "913" "944" "975" "1370"
[19] "1401" "1431" "1097" "1128" "1156" "1187" "1217" "1248" "1309"
[28] "1340" "1735" "1766" "1796" "1462" "1493" "1521" "1552" "1582"
but then I don't know how to sort them.
Many thanks
Upvotes: 2
Views: 8827
Reputation: 21471
You can find the order you need for it to be sorted by using order(names(myfilesContent))
, this can then be used to subset what you want (this is not clear to me).
This works, because it's possible to sort strings. The only issue you might have is that the strings have to be of equal length (you need to append 0's).
Then you can use myfilesContent[order(names(myfilesContent)), ]
to order, given that myfilesContent is a matrix
For the appending 0's you could use something like this:
a = names(myfilesContent)
b = mapply(paste0,sapply(nchar(a),function(x) rep("0", max(char(x)) - x + 1)), a)
Which is in fact more complex than I initially thought it would be [!] and you should consider Roland's answer as it addresses the fact that you're dealing with dates.
[!] I thought that paste0(rep("0", max(nchar(a) - nchar(a)), a)
would work.
Upvotes: 1
Reputation: 132969
dates <- do.call(rbind,
strsplit(gsub(".dat", "",
myfiles, fixed=TRUE),
"-"))
dates <- matrix(as.numeric(dates), ncol=2)
myfilesContent[order(dates[,1], dates[,2])]
Upvotes: 4