如何在R或Matlab中使用原始数据和查找表创建新表?

3

我有一个名为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完成这个任务?
3个回答

1
我使用tidyverse提出了一个解决方案。它涉及一些宽到长的转换,将数据框匹配到Station上,然后展开变量。
#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

谢谢你的输入。我想从文本文件中读取数据,而不是在代码本身中给出数据。 - user6985
你的文件分隔符是什么? - Henry Cyranka

1
这是一个与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',' ')

0
我们可以使用基本的R语言来实现这个。通过将“Station”列与第一个数据集的“names”匹配,创建一个列索引,使用它来复制“df1”的列,然后使用第二个数据集的“ID”列更改列名称。请保留html标签。
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

数据

df1 <- structure(list(Date = c("1/1/2001", "1/2/2001", "1/3/2001", "1/4/2001", 
"1/5/2001"), `101` = c(25L, 23L, 22L, 21L, 22L), `102` = c(24L, 
20L, 21L, 27L, 30L), `103` = c(23L, 15L, 17L, 18L, 19L)), 
 class = "data.frame", row.names = c(NA, 
-5L))

df2 <- structure(list(ID = 1:5, Station = c(101L, 103L, 102L, 101L, 
102L)), class = "data.frame", row.names = c(NA, -5L))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接