for loop and sapply for assigning name
0
0
Entering edit mode
9 weeks ago
Bio • 0

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 • 172 views
ADD COMMENT
0
Entering edit mode

Untested since no example data was provided.

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

Login before adding your answer.

Traffic: 2489 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6