用R创建一个数据框,其中列名是动态指定的

13

我需要创建一个数据框,它将逐行通过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。

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

看起来是朝着正确的方向前进,但我需要"展开"它以创建所需的数据框结构。

请问你能给予建议吗?


每一列需要属于哪个类? - mdsumner
3个回答

10
这有帮助吗?
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")

基本上,我首先创建了一个名为output的数据框,并在下一步中命名这些列。但是,请注意mdsumner的评论!这种方法会使所有列的类别都是numeric。不过,您可以稍后处理: 更改数据框中多个列的类别


谢谢 - 这个方法可行(尽管之后必须去掉第一行全零)。除了日期列,所有列都是数字(前两列是整数参考号码;其余都是浮点数)。 - Rob Forsyth
@RobForsyth既然你说你正在循环遍历行来填充那个数据框,我认为你只需要从第一行开始并替换那里的零。此外,这应该会自动覆盖列类。你的问题解决了吗?还是你在寻找其他东西?如果是前者,如果你能接受我的或Allan的答案,那就好了,这样就可以不再列表中显示了。否则,如果你能提供更多细节,我可以再试一次;-)或者也许有人有更好的解决方案(我想肯定有)。 - Christoph_J
抱歉 - 我对Stackoverflow的礼仪还不熟悉!现在已标记为已回答:再次感谢! - Rob Forsyth
没关系,我也花了一段时间才适应 Stack Overflow。欢迎加入并很高兴能帮到你。 - Christoph_J

6
如果可以先用一些数据填充框架,那么您只需分配名称()即可。否则,您需要先创建列表(然后稍后转换为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

希望这可以帮助您。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接