任何 R 专家都可以提供一种更快的方法来执行以下操作吗?我的代码有效,但需要 1 分钟才能完成 30,000-[column] x 12-[row] 数据框。谢谢!
sync.columns = function(old.data, new.colnames)
{
# Given a data frame and a vector of column names,
# makes a new data frame containing exactly the named
# columns in the specified order; any that were not
# present are filled in as columns of zeroes.
if (length(new.colnames) == ncol(old.data) &&
all(new.colnames == colnames(old.data)))
{
old.data # nothing to do
}
else
{
m = matrix(nrow=nrow(old.data),ncol=length(new.colnames))
for (t in 1:length(new.colnames))
{
if (new.colnames[t] %in% colnames(old.data))
{
m[,t] = old.data[,new.colnames[t]] # copy column
}
else
{
m[,t] = rep(0,nrow(m)) # fill with zeroes
}
}
result = as.data.frame(m)
rownames(result) = rownames(old.data)
colnames(result) = new.colnames
result
}
}
也许与cbind有关?