简体   繁体   English

如何从 R 环境中的第一行为多个数据帧分配列名

[英]how to assign colnames for multiple dataframes from their first row in R environment

I am listing all the data frames in a vector and doing different operations on data frames by calling them from the vector (list_all).我列出了向量中的所有数据帧,并通过从向量 (list_all) 调用它们对数据帧执行不同的操作。 I am trying to assign colnames to each dataframe using its first row.我正在尝试使用第一行为每个数据框分配列名。

#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,]))
  }

When I run this code line by line it works but when I make funtion and run that funtion I am getting error当我逐行运行此代码时,它可以工作,但是当我创建函数并运行该函数时,出现错误

"Error in get(noquote(list_all[t])) : object 'NA' not found". “get(noquote(list_all[t])) 错误:未找到对象‘NA’”。 Help me out帮帮我

Like the above comments suggest, it should be easier to deal with this when importing data, eg read.table(..., header = TRUE) . 就像上面的注释所建议的那样,导入数据时应该更容易处理,例如read.table(..., header = TRUE)

Yet, if you somehow cannot to do it, this solution may work for you: 但是,如果您以某种方式无法做到,则此解决方案可能对您有用:

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)))
}
# put into a list and convert first row to header
list_all <- list(df1, df2, df3)

#convert first row to header
list_all <- lapply(
  list_all,
  function(df) {
    names(df) <- lapply(df[1, ], as.character)
    df <- df[-1,] 
    return(df)
  }
)

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

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