通过R中的循环填充数据帧

时间:2013-07-20 16:24:40

标签: 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()将不会填充任何内容。

请帮忙。

1 个答案:

答案 0 :(得分: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 ...