Home > Net >  Using file names as column name in R
Using file names as column name in R

Time:08-13

I have a dataframe that has the cols : and with a filename: ABCD0001-01.filt

ID   Allele   Sample
Id_1   x         10
Id_2   y          3
Id_2   z          5
...

I wish to change the third col of the df to be a part of the filename

ID   Allele   ABCD0001-01
Id_1   x         10
Id_2   y          3
Id_2   z          5
...

How can I achieve this? I understand to use str_split_fixed to seperate .filt from the filename, but have not found a way to incorporate that string into the col name. Please help! Thank you

CodePudding user response:

Try something like this:

> filename="ABCD0001-01.filt"
> df=data.frame(ID=c("Id_1","Id_2","Id_2"),Allele=c("x","y","z"),Sample=c(10,3,5))
> colnames(df)[3]=strsplit(filename,"\\.")[[1]][1]
> df
    ID Allele ABCD0001-01
1 Id_1      x          10
2 Id_2      y           3
3 Id_2      z           5

CodePudding user response:

A dplyr solution

library(dplyr)
library(stringr)
df %>% 
  rename_with(~str_replace(filename, "\\..*", ""), "Sample")
  • Related