我正在使用 R 編程語言。
我撰寫了以下代碼,它創建了 50 個隨機資料集,以“i”為索引:
results <- list()
for (i in 1:50) {
x_i = rnorm(100,1,1)
y_i = rnorm(100,1,1)
z_i = x_i^2 y_i^2 - 10*(cos(2*pi*x_i) cos(2*pi*y_i))
my_data_i = data.frame(x_i, y_i, z_i)
my_data_i$iteration = i
results[[i]] <- my_data_i
}
results_df <- do.call(rbind.data.frame, results)
X<-split(results_df, results_df$iteration)
我試圖將此代碼的結果輸出為 2 種不同的格式:
1)
head(results_df)
x_i y_i z_i iteration
1 1.40961448 1.2457421 11.7016599 1
2 -0.57995713 0.9573615 0.3739812 1
3 1.41691144 1.5326736 22.8146703 1
4 2.37191691 1.4067927 22.8714206 1
5 0.05199839 1.6663260 -1.6731452 1
6 1.55276440 1.1400349 6.7936643 1
2)
head(X)
$`47`
x_i y_i z_i iteration
4601 0.1934291501 -0.276897671 -1.68399306 47
4602 -0.9259593146 0.147881940 -14.04299215 47
4603 1.7537230121 0.037046456 -6.88729779 47
4604 -0.5262735315 1.519582764 22.37454393 47
4605 3.8616108889 0.126078408 1.45304131 47
4606 0.7257319810 1.109770193 -4.43714870 47
我的問題:是否可以為每個唯一的“索引”創建 50 個單獨的資料集?例如:my_data_1、my_data_2、my_data_3 等。
謝謝!
uj5u.com熱心網友回復:
是的,你可以,雖然你不應該。
完成這個壞主意的最簡單方法是list2env
## name appropriately and put them in the global environment
names(results) = paste0("my_data_", seq_along(results))
list2env(results, envir = .GlobalEnv)
(我還要注意,您的 . 與您的.X相同,是資料框串列,所有這些資料框合并為 1,然后您拆分回從 . 開始的位置。)resultsresultsresults_dfXresults
有關為什么不應該這樣做的討論,請參閱我在如何制作資料框串列中的回答?. 通常,使用串列中的資料框或組合成一個資料框比單獨的順序命名物件更容易、更不容易出錯且更具可讀性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/429394.html
上一篇:未在回圈中重新分配變數
