如何在R或matlab中从原始数据和查找表创建新表?

如何在R或matlab中从原始数据和查找表创建新表?,r,matlab,R,Matlab,我在table1.txt中有原始温度数据,其站号标题为 Date 101 102 103 1/1/2001 25 24 23 1/2/2001 23 20 15 1/3/2001 22 21 17 1/4/2001 21 27 18 1/5/2001 22 30 19 我有一个查找表文件lookup.txt,

我在table1.txt中有原始温度数据,其站号标题为

Date       101    102    103    
1/1/2001   25     24     23      
1/2/2001   23     20     15      
1/3/2001   22     21     17      
1/4/2001   21     27     18     
1/5/2001   22     30     19     
我有一个查找表文件lookup.txt,其内容如下:

ID  Station
1   101
2   103
3   102
4   101
5   102
现在,我想创建一个新表new.txt,其ID号标题应为

    Date        1      2       3     4     5    
    1/1/2001   25     23      24     25    24
    1/2/2001   23     15      20     23    20
    1/3/2001   22     17      21     22    21
    1/4/2001   21     18      27     21    27
    1/5/2001   22     19      30     22    30

在R或matlab中是否还有其他方法可以实现这一点

我用tidyverse想出了一个解决方案。它涉及一些从宽到长的转换,匹配站点上的数据帧,然后传播变量

#Recreating the data

library(tidyverse)

df1 <- read_table("text1.txt")

lookup <- read_table("lookup.txt")

#Create the output
k1 <- df1 %>% 
       gather(Station, value, -Date) %>%
       mutate(Station = as.numeric(Station)) %>%
       inner_join(lookup) %>% select(-Station) %>%
       spread(ID, value)

k1
我们可以使用base R来实现这一点。通过将“Station”列与第一个数据集的名称匹配来创建列索引,使用该列复制“df1”的列,然后使用第二个数据集的“ID”列更改列名

i1 <- with(df2, match(Station, names(df1)[-1]))
dfN <- df1[c(1, i1 + 1)]
names(dfN)[-1] <- df2$ID
dfN
#      Date  1  2  3  4  5
#1 1/1/2001 25 23 24 25 24
#2 1/2/2001 23 15 20 23 20
#3 1/3/2001 22 17 21 22 21
#4 1/4/2001 21 18 27 21 27
#5 1/5/2001 22 19 30 22 30
数据
以下是MatLab的一个选项:

T = readtable('table1.txt','FileType','text','ReadVariableNames',1);
L = readtable('lookup.txt','FileType','text','ReadVariableNames',1);
old_header = strcat('x',num2str(L.Station));
newT = array2table(zeros(height(T),height(L)+1),...
    'VariableNames',[{'Date'} strcat('x',num2cell(num2str(L.ID)).')]);
newT.Date = T.Date;
for k = 1:size(old_header,1)
    newT{:,k+1} = T.(old_header(k,:));
end
writetable(newT,'new.txt','Delimiter',' ')

嗨,谢谢你的意见。我想从文本文件中读取,而不是在代码中给出数据。文件的分隔符是什么?
T = readtable('table1.txt','FileType','text','ReadVariableNames',1);
L = readtable('lookup.txt','FileType','text','ReadVariableNames',1);
old_header = strcat('x',num2str(L.Station));
newT = array2table(zeros(height(T),height(L)+1),...
    'VariableNames',[{'Date'} strcat('x',num2cell(num2str(L.ID)).')]);
newT.Date = T.Date;
for k = 1:size(old_header,1)
    newT{:,k+1} = T.(old_header(k,:));
end
writetable(newT,'new.txt','Delimiter',' ')