[英]Create an data.frame in R with dynamically assigned column names
我需要创建一个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")
似乎是朝着正确方向迈出的一步,但我需要“压扁”它以创建所需的data.frame结构
你能告诉我吗?
这有帮助吗?
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
类。 您可以稍后处理: 更改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
希望这可以帮助
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.