mr_swap
mr_swap

Reputation: 341

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). 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". Help me out

Upvotes: 0

Views: 152

Answers (2)

JMonroe
JMonroe

Reputation: 1

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

Upvotes: 0

ytu
ytu

Reputation: 1850

Like the above comments suggest, it should be easier to deal with this when importing data, e.g. 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)))
}

Upvotes: 2

Related Questions