有办法做到这一点吗?
我被这个卡住了:
m <- 10 # nof row
n <- 5 # nof column
# We will fill each cell with '0'
all <-c()
for (i in 1:m) {
row_i <- c(rep(0,n))
all <- c(all,row_i)
}它只创建1行作为输出。
发布于 2012-05-11 10:05:29
为什么不使用矩阵呢?data.frames用于存储不同类型的列。
所以,
m = 10
n = 5
mat = matrix(0, nrow = m, ncol = n)如果你真的想要一个data.frame,强制使用一个--列名将是默认的:
dat = as.data.frame(mat)
names(dat)
[1] "V1" "V2" "V3" "V4" "V5"你的方法的问题是,你只是简单地一个接一个地追加这些值,而忽略了你需要的尺寸。你可以这样做,但是增加数据不是一个好主意,更好的办法是像上面那样预先分配它们。另外,这会产生一个矩阵,我认为这是你应该使用的。
警告:前面有错误的代码!
m <- 10 # nof row
n <- 5 # nof column
all <- NULL
for (i in 1:m) {
row_i <- c(rep(0,n))
all <- rbind(all,row_i)
}发布于 2012-05-11 12:30:50
这将生成以零填充的data.frame。
as.data.frame(lapply(structure(.Data=1:N,.Names=1:N),function(x) numeric(M)))https://stackoverflow.com/questions/10544442
复制相似问题