How to split the file name from the path and covert into a separate vector

I created a list with read.table() that looks like this:

V1 V2
1 23k ./foo/bar/test.bam
2 34k ./hey/you/test2.bam
3 100G ./to/far/to/go/test3.bam

How can I split the file name from the path and convert it into a separate vector (V3)?

You can use dplyr, base r, or the fs package. I prefer the fs package, but any will work.

### Data
data <- tibble(
  V1 = c("23k", "34k", "100G"), 
  V2 = c("./foo/bar/test.bam", "./hey/you/test2.bam", "./to/far/to/go/test3.bam")

data %>%
  mutate(`File Path` = basename(V2))

### Base R
data$`File Path` <- basename(data$V2)

### FS
data$`File Path` <- path_file(data$V2)
data$`File Directory` <- path_dir(data$V2)

When testing the dplyr method, I get the desired third vector, but I also want the file name removed from the V2 column. How can I get that. In other words, the three columns I'm looking for will display V1 (the size), V2 (the path), and V3 (the file name).

Just use the fs package along with dplyr.

data %>%
     mutate(V3 = path_file(V2), 
            V2 = path_dir(V2))

Thanks. This worked like a charm.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.