Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to paste all columns at once

Is there a way to paste all columns at once in a dataframe

asd <- data.frame(a = c("A", "B"), b = c(1,2))

I need to paste all columns (a and b) and and alter column A as below

asd$a <- paste0(asd$a, "_", asd$b)

But is there a way to automate because, if a dataframe has many columns (a, b, c and so on).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

asd <- data.frame(a = c("A", "B"), b = c(1,2), c = c(1,2), x = c(1,2))

Expected output (need to combine only a, b and c)

asd
      a    b  c  x
1 A_1_1    1  1  1
2 B_2_2    2  2  2

we can do it using asd$a <- paste0(asd$a, "_", asd$b, "_", asd$c) but looking for some simple approach.

I tried with below function but not working


paste_function <- function(df, df_col = c(a, b)){
  for (i in df_col){
    return(substr(paste0(df,'$',df_col,collapse = ",", sep = ",'_'"), 1,nchar(paste0(df,'$',df_col,collapse = ",", sep = ",'_'"))-4))
  }
}

asd$a <- paste_function(asd, df_col = c(a, b, c))

>Solution :

use do.call

asd$a <- do.call(paste, c(asd, sep = '_'))
asd
        a b c d
1 A_1_1_1 1 1 1
2 B_2_2_2 2 2 2

Other ways include:

rlang::exec(paste, !!!asd, sep = '_')
purrr::lift(paste)(asd, sep = '_') # deprecated
purrr::invoke(paste, asd, sep = '_') # deprecated
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading