I need to open multiple txt (all have the same number of variables and variables names, see picture[1]); to each, add multiple columns with specific parts of their file name; then save a CSV resulting from merging all txts, with the added columns corresponding to each txt unique file name.
The file name looks like:
NVR_ch2_main_20220505140000_20220505150000
and I need three columns:
Month (05, the first of the two after 2022),
Day (05) and
hour (14).
Example of one of the txt sources of datawould
dput(head('NVR_ch2_main_20220505132105_20220505140000.txt'))
# A tibble: 41 x 8
Selection View Channel Begin Time (s) End Time (s) Low Freq (Hz) High Freq (Hz)
type <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 1 Waveform 1 1 790. 792. 0 4000 NA
# ... with 37 more rows
I managed the process with the whole file name for one file:
read_tsv('NVR_ch2_main_20220505132105_20220505140000.txt') %>%
mutate(filename = 'NVR_ch2_main_20220505132105_20220505140000.txt') %>%
select(filename, everything ()) %>%
write_csv('C:/Users/marta/Documents/R/Crete/NVR_ch2_main_20220505132105_20220505140000.csv')
You may have to adjust the numbers that are in the
str_sub()calls so that you get the right position from the file names.Note the the columns will be probably be characters. If you need numbers for
month,day, andhour, you should changestr_sub()toas.numeric(str_sub()).