我列出了向量中的所有数据帧,并通过从向量(list_all)调用它们对数据帧执行不同的操作。我正在尝试使用第一行为每个数据帧分配colnames。
#table_1
V1 V2 V3 V4 V5
1: caffeine ACHE Adora1 ADORA1 Adora2a
2: 7.25- 7.25 15.00- 44.00 44.00- 49.00 9.40- 48.10
#table_2
V1 V2
1: paraxanthine daf-12
2: NA
#table_3
V1 V2 V3 V4
1: theophylline Adora1 ADORA1 Adora2a
2: 0.70- 26.00 0.00- 20.00 1.31- 25.30
list_all <- c("table_1","table_2","table_3") # this list was derived from previous code of 60 lines
n_drugs <- 3
drug_names <- c("caffeine","paraxanthine","theophylline")
output_final <- matrix(ncol=n_drugs , nrow=1)
for (t in 1:length(list_all)){
output_final[t] <- paste(drug_names[t],"output_final", sep = "_")
names_all <- c()
names_all[t,] <- unlist(c(as.character(get(noquote(list_all[t]))[1,]))) #saving colnames in 'names_all'
names_all[t,1] <- c("drug_name") # change first column name
assign(output_final[t],setnames(get(noquote(list_all[t])),colnames(get(noquote(list_all[t]))),names_all[t,]))
}
当我逐行运行此代码时,它可以正常工作,但是当我制作功能并运行该功能时,我收到错误
&#34; get中的错误(noquote(list_all [t])):object&#39; NA&#39;找不到&#34;。帮帮我
答案 0 :(得分:2)
与上述评论相似,在导入数据时应该更容易处理此问题,例如: read.table(..., header = TRUE)
。
然而,如果你不能这样做,这个解决方案可能对你有用:
set_first_row_name <- function(X) {
X <- as.data.frame(X)
# X should be a data frame
names(X) <- X[1,]
X[-1,]
}
for (the_one_table in list_all) {
# list_all is your created name list of tables
# Do set_first_row_name to each table and assign them back respectively
assign(the_one_table, set_first_row_name(get(the_one_table)))
}