1

我正在尝试通过循环填充数据框。我在一定程度上成功了,但无法在函数中绑定该循环

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() 什么都不会填充。

请帮忙。

4

1 回答 1

1

看起来它应该产生一个结果。您需要将 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 ...
于 2013-07-20T16:32:21.813 回答