代码之家  ›  专栏  ›  技术社区  ›  user6985

根据从matlab或R中的第二个文件中选择的标题从文件中提取列

  •  0
  • user6985  · 技术社区  · 7 年前

    我有一个大的文本表,标签分开。第一行是标题。然后,我有第二个文本文件,其中包含第一个文件中标题的子集。我想提取第一个文件的所有列,其标题包含在第二个文件中给出的列表中。以下是输入和所需输出的示例:

    数据txt文件

     head0 head1 head2 head3 head4  
     1 25 1364 22 13  
     2 10 215 1 22 
    

    列表txt文件

    head0  
    head4 
    

    所需输出

    head0 head4  
    1 13  
    2 22
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   akrun    7 年前

    我们可以使用 base R 用于此的方法

    df1[df2[[1]]]
    

    数据

    #specify the `sep` as well
    df1 <- read.table('Data.txt', header = TRUE, stringsAsFactors = FALSE)
    df2 <- read.table('List.txt', header = FALSE, stringsAsFactors = FALSE)
    
        2
  •  1
  •   Matias Andina    7 年前

    我想 R 这样做很简单(因为您可以轻松读取数据)。可能是这样的

    mydata <- read.table('data_filename.txt', header=T, ...)
    
    # This one looks like header=F in your example...not quite sure how your data is structured
    mycolumns <- read.table('columns_filename.txt', header=F, ...)
    
    # x should be the name of the column
    final_data <- dplyr::select(mydata, mycolumns$x)
    

    代码不完整,但应该很容易计算出详细信息 它也可以通过子集在基R中完成(参见其他答案)。