2017-06-02 67 views
1

我一直在嘗試將循環的結果寫入csv。我試圖在20列的每一列中對數據進行排名。我正在使用的循環是:在r中寫入結果循環的結果

for (i in 1:ncol(testing_file)) { 
    print(rank(testing_file[[i]])) 
} 

這可以工作並將預期結果打印到屏幕上。我已經嘗試了很多在各種討論中提出的方法來將這個結果寫入文件或數據框架,大部分沒有運氣。 我就包括我最有前途的鉛,它返回正確的數據只有一列,以「測試」的列標題:

for (i in 1:ncol(testing_file)) { 
    testing<- (rank(testing_file[[i]])) 
    testingdf <- as.data.frame(testing) 
} 

任何幫助,不勝感激!

回答

0

我不好跟嵌套循環,所以我想嘗試:

testing_file <- data.frame(x = 1:5, y = 15:11) 
testing <- as.data.frame(lapply(seq_along(testing_file), function (x) 
rank(testing_file[, x]))) 

> testing_file 
x y 
1 1 15 
2 2 14 
3 3 13 
4 4 12 
5 5 11 

,並讓你出凌亂的嵌套循環。在寫入csv之前,你想檢查rank()的結果嗎?

或只是把它包在write.csv,該colnames將原來的DF colnames:

> write.csv(testing <- as.data.frame(lapply(seq_along(testing_file), 
function (x) rank(testing_file[, x]))), "testing.csv", quote = FALSE) 
+0

謝謝你的建議。我試過這些選項,但得到的錯誤: 不支持使用矩陣或列索引 – Crissy

+0

我發現了一個解決方案:testage < - data.frame(matrix(,nrow = 73,ncol = 20)) (測試文件) (testage)< - colnames(testing_file) – Crissy

1

我發現,有效的解決方案:

testage<- data.frame(matrix(, nrow=73, ncol=20)) #This creates an empty data 
frame that the ranked results will go into 
for (i in 1:ncol(testing_file)) { 
testage[i] <- rank(testing_file[[i]]) 
print(testage[i]) 
} #this is the loop that ranks data within each column 
colnames(testage) <- colnames(testing_file) #take the column names from the 
original file and apply them to the ranked file. 
+0

和(測試文件)(測試文件)我想現在你接受你的答案。乾杯。 – Chris