0

I have a number of equally sized matrices in a list:

enter image description here

I merged them with Reduce and join:

env.all <- Reduce(function(...) left_join(..., by = c('X1', 'X2')), dists.can) 

But since all the joinable columns in the data.frames are equally called "value", the names of the new data.frame are awkward:

names(env.all)
[1] "X1"            "X2"            "value.x"       "value.y"       "value.x.x"     "value.y.y"     "value.x.x.x"   "value.y.y.y"  
 [9] "value.x.x.x.x" "value.y.y.y.y" "value" 

In order to prevent this, i thought of renaming each column $value in dist.can with the name of the parental data.frame, so that eg. dist.can$aridity$value becomes e.g. "dist.can$aridity$aridity".

dists.can <- lapply(dists.can, function(x) {names(x$value) <- names(x);x})

But this failed. It does nothing. How can i achieve this?

toy data:

dist.can <- list(Name1=data.frame(X1=LETTERS[1:10], X2=letters[1:10], value=runif(10)),
     Name2=data.frame(X1=LETTERS[1:10], X2=letters[1:10], value=runif(10)),
     Name3=data.frame(X1=LETTERS[1:10], X2=letters[1:10], value=runif(10)))
nouse
  • 3,315
  • 2
  • 29
  • 56

1 Answers1

1

You did not share with what you want to replace the value column. We can add list name as prefix. Also names(x$value) is naming the values in value, not the column name.

Map(function(x, y) {names(x)[names(x) == 'value'] <- paste0('value_', y);x},
                    dist.can, names(dist.can))

Perhaps, simpler in tidyverse :

library(dplyr)
library(purrr)

imap(dist.can, ~.x %>% rename_with(function(x) paste0('value_', .y),value))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thank you. that was indeed not clear from my question, so i edited it. You managed however to grasp it, anyway, and your solution works well. – nouse Jul 26 '20 at 15:24