r函数从命名向量添加到数据帧列

时间:2017-12-24 10:21:51

标签: r function loops dataframe

我正在尝试使用函数将从列表中提取的命名向量添加到数据框中(我需要添加大量此类向量)。 我从一个空数据帧开始,并希望添加一个名称出现在向量中的向量。

让我们从一个非常简单的例子开始:

set <-c("c1", "c190", "c200","c66")

fun1<-function(z){
    dataf <-data.frame(matrix(, nrow=4))
    v1<-c(1, 2, 3, 4)
    for(i in z){
    dataf[i] <- c(1, 2, 3, 4)
    }   
    return(dataf)
    }
test <- fun1(set)   

这完美无缺!例如,test$c1为我提供了具有正确值的正确向量。

现在,我尝试为我的数据做这件事,这有点复杂。 我有一年矢量,年份&lt; -c(“y2003”,“y2004”等...) 我还有一个变量数据框命名变量,每组变量“c1”,“c2”等数据向量。基本上colnames(变量)== set。 在前面的例子中,我希望获得的向量是异构的(c(1,2,3,4)),现在我首先需要计算它:

rci_set <- function(x, y, set){ #x is a list, y my year vector and set the UNIQUE variable I wish to get the data from
    vector <-c()
    for(i in y){
    vector <-c(vector, x[[i]][set])
    }
    vector2<-as.numeric(vector)
    return(vector2)
    }   

再次,这完美地运作了!

然后,我想为我的所有集合循环:

all_rci<-function(x, y, z){ #x is the same list, y the same year vector, z the set vector I wish to loop
    dataf <-data.frame()
    for(i in z){
        dataf[i] <- rbind(dataf, data.frame(rci_set(x, y, z[i]))) 
        }
    return(dataf)
    }

这不起作用,我收到错误:“找不到列NA” 我已经多次检查过,并且在我的所有数据中都没有名为NA的列。什么地方出了错 ? 也许我可以使用apply函数更快地完成它,但同样,我没有设法找到它。

非常感谢您提供的任何帮助:)

0 个答案:

没有答案