【问题标题】:extract columns from file based on header selected from 2nd file in matlab or R根据从 matlab 或 R 中的第二个文件中选择的标题从文件中提取列
【发布时间】:2018-09-15 22:10:32
【问题描述】:

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

数据.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

【问题讨论】:

  • 使用read.table读取两个数据集,然后使用df1[df2[[1]]如果第二个数据集列是factor,则将其转换为characterdf1[as.character(df2[[1]])]

标签: r matlab indexing subset


【解决方案1】:

我们可以为此使用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】:

    我认为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 中完成(参见其他答案)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 2014-07-13
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      相关资源
      最近更新 更多