1

I have a list of dataframes with varying dimensions filled with data and row/col names of Countries. I also have a "master" dataframe outside of this list that is blank with square dimensions of 189x189.

I wish to merge each dataframe inside the list individually on top of the "master" sheet perserving the square matrix dimensions. I have been able to achieve this individually using this code:

rownames(Trade) <- Trade$X
Trade <- Trade[, 2:length(Trade)]

Full[row.names(Trade), colnames(Trade)] <- Trade

With "Full" being my master sheet and "Trade" being an individual df.

I have attempted to create a function to apply this process to a list of dataframes but am unable to properly do this.

Function and code in question:

  DataMerge <- function(df) {

    rownames(df) <- df$Country
     Trade <- Trade[, 2:length(Trade)]
    
    Country[row.names(df), colnames(df)] <- df
  
  }

Applied using :

DataMergeDF <- lapply(TradeMatrixDF, DataMerge)
filenames <- paste0("Merged",names(DataMergeDF), ".csv")
mapply(write.csv, DataMergeDF, filenames)

Country <- read.csv("FullCountry.csv")

However what ends up happening is that the data does not end up merging properly / the dimensions are not preserved.

I asked a question pertaining to this issue a few days ago (CSV generated from not matching to what I have in R) , but I have a suspicion that I am running into this issue due to my use of "lapply". However, I am not 100% sure.

6
  • Do you have a matrix or data.frame. Inside the function you have Country as the data, but outside there is Full, which one is correct Commented Jul 31, 2021 at 21:39
  • I would suggest to include a small reproducible example to test. Commented Jul 31, 2021 at 21:46
  • Also, I think your function should return the Country after the assignment i.e. return(Country)} Commented Jul 31, 2021 at 21:50
  • 1
    Trade <- Trade[, 2:length(Trade)] is redundant inside function unless you meant df <- df[, 2:length(df)]. Commented Jul 31, 2021 at 22:09
  • @Parfait I didn't notice that difference. Thanks for mentioning it Commented Jul 31, 2021 at 23:39

1 Answer 1

2

If we return the 'Country' at the end it should work. Also, better to pass the other data as an argument

DataMerge <- function(Country, df) {

    rownames(df) <- df$Country
     df <- df[, 2:length(df)]
    
    Country[row.names(df), colnames(df)] <- df
    Country
  
  }

then, we call the function as

DataMergeDF <- lapply(TradeMatrixDF, DataMerge, Country = Country)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.