簡體   English   中英

通過R中的循環填充數據幀

[英]Populating data frame through loop in R

我正在嘗試通過循環填充數據幀。 我在一定程度上成功了,但是無法將循環綁定到一個函數中

iterations = 34
variables = 6
v_log <- matrix(ncol=variables, nrow=iterations)

for (i in 1:34)
{
    v_log[i,]<-c(1,"c1", "c2","c3", "c4", "c5")
}
v_log1=as.data.frame(v_log)

但是當我試圖將它們綁定到函數中時,

f1<- function() {

iterations = 34
variables = 6
v_log <- matrix(ncol=variables, nrow=iterations)

for (i in 1:34)
{
    v_log[i,]<-c(1,"c1", "c2","c3", "c4", "c5")
}
v_log1=as.data.frame(v_log)
}

在執行函數時,像f1()一樣,將不會填充任何內容。

請幫忙。

看起來應該產生結果。 您需要將f1的輸出分配給命名對象,否則它將被垃圾回收。 歡迎使用函數式編程。 您已離開SAS / SPSS宏處理器域:

> test <- f1()
> str(test)
'data.frame':   34 obs. of  6 variables:
 $ V1: Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
 $ V2: Factor w/ 1 level "c1": 1 1 1 1 1 1 1 1 1 1 ...
 $ V3: Factor w/ 1 level "c2": 1 1 1 1 1 1 1 1 1 1 ...
 $ V4: Factor w/ 1 level "c3": 1 1 1 1 1 1 1 1 1 1 ...
 $ V5: Factor w/ 1 level "c4": 1 1 1 1 1 1 1 1 1 1 ...
 $ V6: Factor w/ 1 level "c5": 1 1 1 1 1 1 1 1 1 1 ...

暫無
暫無

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

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