Search code examples
rmultiple-columnscopy-paste

In R, how to print column names into vector form?


I have a dataframe with hundreds of columns. I need to take groups of columns to apply transformations. Having to copy-paste, then insert commas and remove extra space is time-consuming. Here is a dataframe with only 13 columns as an example.

df <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20)
  ,x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20)
  ,x8=rnorm(20),x9=rnorm(20),x10=rnorm(20),x11=rnorm(20)
  ,x12=rnorm(20),x13=c(2,1,1,2,2,1,2,1,2,2,1,1,2,1,2,2,1,2,1,1))

I can print the names, but they look like:

colnames(df)
[1] "x1"  "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "x10" "x11" "x12" "x13"

I want

c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13")

What I have tried:

paste0("c(",paste(names(df),collapse=","),")")
[1] "c(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13)"

paste0("c(",paste(names(df),collapse="\",\""),")")
[1] "c(x1\",\"x2\",\"x3\",\"x4\",\"x5\",\"x6\",\"x7\",\"x8\",\"x9\",\"x10\",\"x11\",\"x12\",\"x13)"

paste0("c(",paste(names(df),collapse="','"),")")
[1] "c(x1','x2','x3','x4','x5','x6','x7','x8','x9','x10','x11','x12','x13)"

paste0("c(",paste(str(names(df)),collapse=","),")")
chr [1:13] "x1" "x2" "x3" "x4" "x5" "x6" "x7" "x8" "x9" "x10" "x11" "x12" "x13"
[1] "c()"

Solution

  • use the dput() function

        df <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20)
                         ,x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20)
                         ,x8=rnorm(20),x9=rnorm(20),x10=rnorm(20),x11=rnorm(20)
                         ,x12=rnorm(20),x13=c(2,1,1,2,2,1,2,1,2,2,1,1,2,1,2,2,1,2,1,1))
    
        x <- colnames(df)
    
        dput(x)
        #> c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", 
        #> "x11", "x12", "x13")
    

    Created on 2020-08-11 by the reprex package (v0.3.0)