0
votes

I have several data frames all with the same colnames. I want to merge two columns in each one of them to create a new column.

data frames looks like this:

enter image description here

I want the output to look like this:

enter image description here

Normally I would do this very easily for one data frame:

a$XY_ID <- paste(a$X,ak$Y,sep=":")

How to do this for all the dataframes in a list?

Thanks for the help!

2

2 Answers

2
votes

You can use paste command in lapply :

dfList <- lapply(dfList, function(x) transform(x, XY_ID = paste(X,Y,sep=":")))

In tidyverse you can use map to iterate over list and unite to combine columns.

dfList <- purrr::map(dfList, ~tidyr::unite(.x, XY_ID, X, Y, sep = ":", remove = FALSE))
1
votes

We can use do.call with paste and it would also work if there are many columns to concatenate

dfList <- lapply(dfList, function(x) {
         x$XYID <- do.call(paste, c(x[c('X', 'Y')], sep=":"))
         x })