簡體   English   中英

R-分割數據框並保存到其他文件

[英]R - split data frame and save to different files

我有一個數據框,其中包含幾個位置的每月溫度數據:

    > df4[1:36,]
       location    variable cut month year freq
1    Adamantina temperature  10   Jan 1981 21.0
646  Adamantina temperature  10   Feb 1981 20.5
1291 Adamantina temperature  10   Mar 1981 21.5
1936 Adamantina temperature  10   Apr 1981 21.5
2581 Adamantina temperature  10   May 1981 24.0
3226 Adamantina temperature  10   Jun 1981 21.5
3871 Adamantina temperature  10   Jul 1981 22.5
4516 Adamantina temperature  10   Aug 1981 23.5
5161 Adamantina temperature  10   Sep 1981 19.5
5806 Adamantina temperature  10   Oct 1981 21.5
6451 Adamantina temperature  10   Nov 1981 23.0
7096 Adamantina temperature  10   Dec 1981 19.0
2        Adolfo temperature  10   Jan 1981 24.0
647      Adolfo temperature  10   Feb 1981 20.0
1292     Adolfo temperature  10   Mar 1981 24.0
1937     Adolfo temperature  10   Apr 1981 23.0
2582     Adolfo temperature  10   May 1981 18.0
3227     Adolfo temperature  10   Jun 1981 21.0
3872     Adolfo temperature  10   Jul 1981 22.0
4517     Adolfo temperature  10   Aug 1981 19.0
5162     Adolfo temperature  10   Sep 1981 19.0
5807     Adolfo temperature  10   Oct 1981 24.0
6452     Adolfo temperature  10   Nov 1981 24.0
7097     Adolfo temperature  10   Dec 1981 24.0
3         Aguai temperature  10   Jan 1981 24.0
648       Aguai temperature  10   Feb 1981 20.0
1293      Aguai temperature  10   Mar 1981 22.0
1938      Aguai temperature  10   Apr 1981 20.0
2583      Aguai temperature  10   May 1981 21.5
3228      Aguai temperature  10   Jun 1981 20.5
3873      Aguai temperature  10   Jul 1981 24.0
4518      Aguai temperature  10   Aug 1981 23.5
5163      Aguai temperature  10   Sep 1981 18.5
5808      Aguai temperature  10   Oct 1981 21.0
6453      Aguai temperature  10   Nov 1981 22.0
7098      Aguai temperature  10   Dec 1981 23.5

我需要做的是以編程方式按位置拆分此數據幀,並為每個位置創建一個.Rdata文件。

在上面的示例中,我將擁有三個不同的文件-Adamantina.Rdata,Adolfo.Rdata和Aguai.Rdata-包含所有列,但僅包含與那些位置相對應的行。

它必須高效且具有程序性,因為在我的實際數據中,我有大約700個不同的位置,每個位置都有大約50年的數據。

提前致謝。

要拆分數據幀,請使用split(df4, df4$location) 它將創建名為AdamantinaAdolfoAguai等的數據幀。

並將這些新數據幀保存到locations.RData文件中,請使用save(Adamantina, Adolfo, Aguai, file="locations.RData") save.image(file="filename.RData")將當前R會話中的所有內容保存到filename.RData文件中。

您可以在此處閱讀有關savesave.image更多信息。

編輯:

如果分割數太大,請使用以下方法:

locations <- split(df4, df4$location)
save(locations, "locations.RData")

locations.RData然后將加載為列表。

這是從先前的答案中借來的,但是我不相信您想要的答案。

首先,按照他們的建議,您想拆分數據集。

splitData <- split(df4, df4$location)

現在,要遍歷此列表,保存數據集,可以通過拔出名稱來完成:

 allNames <- names(splitData)
 for(thisName in allNames){
     saveName = paste0(thisName, '.Rdata')
     saveRDS(splitData[[thisName]], file = saveName)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM