在R中使用动态分配的列名创建data.frame

时间:2012-04-03 09:51:41

标签: r dataframe

我需要创建一个data.frame,它将通过for循环的结果一次填充一行。它有45列:其中五列的名称是静态的,但其余部分在运行时从外部CSV文件读入(作为向量)。我正在寻找符合

的内容
goalsMenu <- read.csv("Phase 1 goalsmenu.csv", header = TRUE)
colHeads <- c("analysis","patient","date",as.vector(goalsMenu$Name),"CR")
output <- data.frame(colHeads)

然而,这会创建一个列名为colHeads的单列data.frame。

colHeads <- list("analysis","patient","date",as.vector(goalsMenu$Name),"CR")

似乎朝着正确的方向迈出了一步,但我需要“平坦化”#34;它来创建所需的data.frame结构

你能告诉我吗?

3 个答案:

答案 0 :(得分:8)

这有帮助吗?

goalsMenu <- paste("Name", 1:40, sep="")
output <- as.data.frame(matrix(rep(0, 5 + length(goalsMenu)), nrow=1))
names(output) <- c("analysis", "patient", "date", goalsMenu, "CR1", "CR2")

基本上,我首先创建一个包含列数的data.frame output,并在下一步中命名这些列。但是,请注意mdsumner的评论!这样,所有列都属于numeric类。您可以稍后处理:change the class of columns in data.frame

答案 1 :(得分:5)

如果您可以先用(某些)数据填充框架,那么您只需指定名称()即可。否则,您必须先创建列表(然后再转换为data.frame):

col.names <- LETTERS[1:10]  # Example column names
data <- vector("list", length(col.names))
names(data) <- col.names
print(str(data))            # Inspect the structure

希望这有帮助

答案 2 :(得分:1)

for (k in c(1:length(names_array))) {
   #Let's make a blank column, that's the length of the data frame that I'm 
   #going to attach it to:

   temp_col<-rep(NA, nrow(my_df))

   # now here's our 2nd loop
   for(i in c(1:nrow(my_df))) {
      #process the col with some stuff
       temp_col[i] <- i
    } 

    # now we're going to attach the column to the last column in the data 
    #frame
    my_df$temp_col<-temp_col

    # now we're going to assign the name from a vector 
    # we do this by looking at the length of the names
    # array, and use that as the index
    names(my_df)[length(names(my_df))]<-names_array[k]
}