[R] How to rename file names with condition
David Winsemius
dw|n@em|u@ @end|ng |rom comc@@t@net
Tue Jul 23 17:37:14 CEST 2019
On 7/23/19 6:30 AM, danielmessay--- via R-help wrote:
> Could somebody please help me on this?
>
> I have many files on my computer and would like to change its names so that it would be more meaningful for me. The filenames are in the following format: cvcvcv198307.xlsx
>
> I want to change it in such a way that
> cvcvcv into Domain1983 want to keep it 07 into 3-1 * And here is my main problem (Explanation below).
>
>
> Each month (01-12) is divided into three data points. Meaning,
>
> 01(Jan) has three data points: 1, 2, and 3
> 02(Feb) has the next three data points: 4,5, and 6...12(Dec) will have: 34,35, and 36
>
>
> So, 01 (last digit in my file name) means, first month, first data point, i.e. 1-1
>
> 02 - First month, and second data point, i.e. 1-2
>
> 03 - First month, third data point, i.e 1-3
>
> 04- second month, first data point, i.e. 2-1
>
> 05- 2-2
>
> 06- 2-3
>
> 07 - 3-1
>
> 08 - 3-2
>
> 09 - 3-3
>
> 10 - 4-1
>
> 11 - 4-2
>
> 12 - 4-3
>
> .
>
> .
>
> .
> 35 - 12-2
> 36 - 12-3
>
> And that's all.
>
> I have tried file.rename along with sapply for my whole sets of data
>
> (1:18,000). But i can only manage to change the file names before the last two #digits.
>
> Expected result.
>
> The whole file names changed from
>
>
> cvcvcv198307.xlsx into Domain1983-3-1.txtcvcvcv198414.xlsx into Domain1984-5-2.txt
>
>
>
>
> (Yes, file name extension too!)
It's not clear which area is causing you difficulty. Clearly you need to
be using `gsub` and the `%/% and `%%` functions: This may help on the
extraction of the month index and modulo arithmetic:
test <- c("cvcvcv198301.xlsx", "cvcvcv198302.xlsx",
"cvcvcv198303.xlsx", "cvcvcv198304.xlsx", "cvcvcv198305.xlsx",
"cvcvcv198306.xlsx", "cvcvcv198307.xlsx")
mon <- as.numeric( gsub(".+(\\d{2})\\.xlsx", "\\1", test) )
(mon +2) %/% 3
#[1] 1 1 1 2 2 2 3
(mon +2) %% 3 +1
#[1] 1 2 3 1 2 3 1
You should now have sufficient examples and be able to use `sub` and
`paste` to modify the file names to suit your requirements.
>
> Thank you guys and I really appreciate any help on this.
> Daniel
>
>
>
> [[alternative HTML version deleted]]
PLEASE: Read the Posting Guide and only post in plain text. Your code
will continue to be mangled because the HTML version is stripped by the
mail server, and teh line breaks get lost.
--
David.
More information about the R-help
mailing list