简体   繁体   English

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

[英]Create an data.frame in R with dynamically assigned column names

I need to create a data.frame that will be populated one row at a time by results of a for loop. 我需要创建一个data.frame,它将通过for循环的结果一次填充一行。 It has 45 columns: the names of five of these are static but the remainder are read in (as a vector) from an external CSV file at run time. 它有45列:其中五列的名称是静态的,但其余部分在运行时从外部CSV文件读入(作为向量)。 I'm looking for something along the lines of 我正在寻找类似的东西

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

however this creates a one-column data.frame with column name of colHeads. 但是这会创建一个列名为colHeads的单列data.frame。

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

seems a step in the right direction but I need to "flatten" it to create the desired data.frame structure 似乎是朝着正确方向迈出的一步,但我需要“压扁”它以创建所需的data.frame结构

could you advise please? 你能告诉我吗?

Does this help? 这有帮助吗?

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")

Basically, I create a data.frame output with the number of columns first and name those columns in the next step. 基本上,我首先创建一个包含列数的data.frame output ,然后在下一步中命名这些列。 However, be aware about mdsumner's comment! 但是,请注意mdsumner的评论! This way, all columns are of class numeric . 这样,所有列都是numeric类。 You can deal with that later though: change the class of columns in data.frame 您可以稍后处理: 更改data.frame中的列类

If you can fill the frame with (some) data first, then you can just assign to names(). 如果您可以先用(某些)数据填充框架,那么您可以只分配名称()。 Otherwise, you'll have to make the list first (and then later convert to data.frame): 否则,您必须先列出该列表(然后再转换为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

Hope this helps 希望这可以帮助

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]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM