如何从文本文件的内容中提取名称?

时间:2015-07-22 09:12:24

标签: r

我有一个文本文件,可以读作:

    file=read.table("C:\\data.txt", sep="")
    > class(file)
   [1] "data.frame"
    > head(file)
    name     bat     cat co ro
 1 face     2        16 25  96

我在目录中有许多文本文件,可以列为:

   dir<- list.files("C:\\datasets", "*.txt", full.names = TRUE)

文件的名称如下:

     ds_ds_df_2011_ 25_96.txt
     this corresponds to:
    ds_ds_df_2011_ co_ro.txt # co ro change while the rest is the same in all files.

其中cofile$corofile$ro

我需要的是将name中相应的file$name添加到文件名中,以便: ds_ds_df_2011_ co_ro_name.txt

这可能吗?

2 个答案:

答案 0 :(得分:2)

因为你似乎懒得自己尝试:

library(stringr)

sapply(dir,function(x) { 
             val <- str_match(x,"ds_ds_df_2011_ (\\d+)_(\\d+).txt")         
             dest <- paste0( sub(".txt$","",x), "_", df$name[df$co==val[2] & df$ro==val[3]],".txt") 
             file.rename(x,dest)  
           })

在dest行中做了什么:

  • sub(".txt","",x)从文件名中删除.txt
  • df$name[df$co==val[2] & df$ro==val[3]]从数据框中获取名称,其中co和ro是从之前的文件名中提取的值。
  • paste0(...)将文件名的开头,下划线,从df中提取的名称和.txt扩展名一起粘贴

我使用的是df而不是原来的file。通用建议:永远不要使用关键字作为变量名,否则会导致问题。

在使用之前备份文件。

答案 1 :(得分:0)

这是一个使用match()在数据框中查找正确名称(此处命名为df)并且不需要任何包的版本。但请注意,它假定dir中文件名的顺序与df中的行排序相匹配。

df <- data.frame(name = c("face", "head"), bat = seq(2), cat = c(16, 26), co = c(25, 35), ro = c(96, 106))
dir <- c("ds_ds_df_2011_ 25_96.txt", "ds_ds_df_2011_ 35_106.txt")

sapply(dir, function(x) {
  sub("\\.", paste0("_", df$name[match(x, dir)], "."), x)
})

以下是该输出:

        ds_ds_df_2011_ 25_96.txt        ds_ds_df_2011_ 35_106.txt 
 "ds_ds_df_2011_ 25_96_face.txt" "ds_ds_df_2011_ 35_106_head.txt"
相关问题