This is a test version of Biostars. For the public version, visit https://www.biostars.org.
for loop and sapply for assigning name

Hi, I would like to change dataframe column names based on info id matching and select names from name column.

I tried to do it separately and it works. Here is the code.

colnames(df1) = sapply(colnames(df1), function(x) {
     info$name[which(info$id == x)]
   })

But when I am trying to do the same thing using for loop to do the same for two data frames,it does nothing.

for(df in c(colnames(df1), colnames(df2)){
     df = sapply(df, function(x) {
     info$name[which(info$id == x)]
   })
}

Can someone help me to understand what I am doing wrong. Any help much appreciated!

r

Untested since no example data was provided.

dfs <- lapply(list(df1, df2), \(x) {
  colnames(x) <- info$name[which(info$id == colnames(x))]
  return(x)
})

0 answers

No answers yet.

Log in to answer this question.