How to add a new column in a data frame and fill column with df filename


I am very VERY new to R and coding. I have imported a .txt file into RStudio but need to add a new column to this data frame with the filename. My code so far:

df <- read.delim("PC120825150001_A1.Table.1.selections.txt", header = TRUE, sep = "\t")

I would like the new column to be filled with 'PC120825150001_A1.Table.1.selections.txt'. Or better yet, just 'PC120825150001'. I have 100's of txt files to convert and plan to create a loop to go through the folder with all the txt files in it.

I have successfully made a new column using df$File <- " ", but not sure what to put in " "

I'm sure it's a quick fix, but I am pulling my hair out :(((

Hello and welcome in the forum,

if you want to just add "PC120825150001" in every row of you new column, you can just use the following:

Data <- data.frame(col1 = 1:3,
                   col2 = LETTERS[1:3])
Data$File <- "PC120825150001"
#>   col1 col2           File
#> 1    1    A PC120825150001
#> 2    2    B PC120825150001
#> 3    3    C PC120825150001

Created on 2022-09-16 by the reprex package (v2.0.1)

So you were basically almost there.

Kind regards

If you're reading in a directory of files (or just a bunch of files that you can put all in one place), there's a nice way to do this with the purrr package described in the following blog post:

Something like this would read all .txt files on a folder into a single data frame with a file_name column.


list_of_files <- list.files(path = "path/to/your/files",
                            recursive = TRUE,
                            pattern = "\\.txt$",
                            full.names = TRUE)

df <- read_delim(list_of_files, id = "file_name", delim = "\t") %>% 
    mutate(file_name = str_extract(file_name, "^.+(?=_)"))

Sorry for the delayed reply, I have been away.

When I run you code there is no output and I get the following message:

── Column specification ────────────────────────────────────────────────────
Delimiter: "\t"
chr (3): View, Freq Contour 50% (Hz), Unit ID
dbl (17): Selection, Channel, Begin Time (s), End Time (s), Peak Freq (Hz), Low Freq (Hz), High Freq (Hz), Delta Time (s), Freq 25% (Hz), Freq 5% ...

:information_source: Use spec() to retrieve the full column specification for this data.
:information_source: Specify the column types or set show_col_types = FALSE to quiet this message.

Not sure where to add this extra information.

Thanks again for your help! :slight_smile:

Thanks for your help!

Each txt file has a different name (i.e. so I will need something that can read the txt filename and use that to populate a new column.