gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:14 24 4
gpt4 key购买 nike

我在 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 的解决方案。它涉及一些从宽到长的转换,匹配 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

关于r - 如何从 R 或 matlab 中的原始数据和查找表创建新表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com