我有一個for loop,& while loop在每次迭代后生成資料。我想將所有資料添加到一個資料框中,但發現很難。因為只有回圈創建的最后一個資料是成功的(可以在下圖中看到:輸出代碼)。
這是代碼,請建議如何修復它:
df = data.frame(matrix(nrow = 350, ncol = 12))
kol<-1
for (x in 1:350) {
output <- c(paste0(x))
df[,1] = output
}
while (kol <= 223) {
if(kol < 224){
rowd1 <- c(paste("gen ",kol))
}
df[,2] = rowd1
kol = kol 1
}#while
while (kol <= 446) {
if(kol < 447){
rowd2 <- c(paste("gen ",kol))
}
df[,3] = rowd2
kol = kol 1
}
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K")
df
所以,我會更新我提出的問題。如果代碼變成這樣怎么辦:問題:行問題
...
for (x in 1:350) {
output <- c(paste0(x))
df[x,1] = output
}
for (x2 in 1:223) {
output2 <- c(paste("Gen ",x2))
df[1,2:224] = output2
}"#why only the value 223 comes out, like the output in the picture 'row problem' that is -Gen 223-"
...
uj5u.com熱心網友回復:
對于 a data.frame df,df[,n]是整個第 n 列。因此,您在每一步都設定了整個列。在您的代碼中,使用
df[x, 1] = output
例如,設定單行的值。
uj5u.com熱心網友回復:
解決了
特別感謝 @JamesHirschhorn,非常感謝您幫助解決問題。并感謝提供反饋的人。
去做
- 可能會遠離
while這里。為什么不直接使用 for 呢?– GuedesBF - 用于
df[x, 1] = output設定第一列中每一行的值
代碼
df = data.frame(matrix(nrow = 350, ncol = 224))
for (x in 1:350) {
output <- c(paste(x))
df[x,1] = output
}
for (x2 in 2:224) {
output2 <- c(paste("Gen ",x2-1))
df[1,x2] = output2
}
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K", ...)
df
輸出:這里 。所以,祝我未來好運
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340136.html
上一篇:根據R中的前一天填寫值
