如何使用一列索引值在单独的数据集中创建新列

How to use a column of index values to create a new column in a separate dataset

我一直无法将两个数据集之间的值耦合在一起,我想知道是否有人可以帮助我。我想我已经接近解决方案,所以希望有人能指出可能出了什么问题。

所以我有两种类型的数据集。一个看起来像这样,我们称它为 dataset1:

1 Asia 
2 Australia
3 Europe

dataset1 包含我的参考集,其中每个数字都链接到一个值。 另一个数据集 dataset2 看起来像这样:

4638  3
14372 3
4464  1
3498  2

我想要做的是使用 dataset2 中第二列的值并在 dataset1 上找到关联的索引值,以便我添加一个新列,如下所示:

4638  3 Europe  
14372 3 Europe  
4464  1 Asia
3498  2 Australia

我试图做的是在第一个数据集中创建一个哈希值,并将它们用作第二个数据库的参考,如下所示:

open($fh, "<", $dataset1) || die "Could not open file $dataset $!/n"; 

while (<$fh>) {
    @tmp = split /\t/, $_;
    $area{$tmp[0]} = $tmp[1];
}

open($fh2, "<", $dataset2) || die "Could not open file $dataset $!/n;

while (<$fh2>) {
   @tmp2 = split /\t/, $_;
    $code = $tmp2[0];
    $index= $tmp2[1];
    if(defined($area{$index})){
        print "$code\t$index\t$area{$index}\n";
    }
}

当我执行上面的命令时,我没有收到任何警告,但也没有打印出任何内容。我假设 "defined" 部分存在问题,但我不确定如何解决它。任何帮助将不胜感激 。

最好的, A.

给你。我使用了哈希引用,因为我喜欢它们我认为你在 \t 上的拆分导致了无法正确映射的主要问题。

EDIT: added chomp and ability to deal with space separated language names

#!/usr/bin/env perl
use strict;
use warnings;

my $ds1_map;

open(my $fh1, "<", 'dataset1') || die "Could not open file dataset1 $!/n"; 
while (my $line = <$fh1> ) {
    chomp($line);
    my @tmp = split(/\s+/, $line);
    my $i = shift @tmp;
    my $str = join(' ', @tmp);
    $ds1_map->{$i} = $str;
}
close $fh1;

open(my $fh2, "<", 'dataset2') || die "Could not open file dataset2 $!/n";
while (my $line = <$fh2>) {
    chomp($line);
    my ($code, $index) = split(/\s+/, $line);
    if(defined($ds1_map->{$index})){
        print "$code\t$index\t$ds1_map->{$index}\n";
    }
}
close $fh2;

这是一种方法,它采用通过 split-ing 引用数据文件中的每一行并将它们的元素 map-ing 到一组散列 [=24] 中创建的匿名数组=].

注意:我已经使用 IO::All 来缩短脚本,以这种方式处理非常大的文件可能效率不高。

use IO::All ;                       
my @idx = io->file("dataset1.txt")->chomp->slurp  ;               
my @data = io->file("dataset2.txt")->chomp->slurp  ;

# make an index hash_ref with successive elements of split lines           
my $index_hr = { map { [split]->[0] => [split]->[1] } @idx };

# print lines where the second element matches index hashref key
foreach my $line (@data) {                                
  my $key = (split /\s+/, $line)[1] ;                              
  print join " ", $line, $index_hr->{$key}, "\n" ;    
}

输出

4638  3 Europe 
14372 3 Europe 
4464  1 Asia 
3498  2 Australia