6

I want to get column names of a data.frame separated with comma (,). I remembered I got this result in past but now forgot the command.

df<- data.frame(x=1:10, y=11:20)
names(df)

Output

"x" "y"

Desired Output

c("x", "y")
2
  • Are you looking for dput(names(df)) perhaps? Nov 28, 2013 at 11:53
  • This is what I need. I remember I used this command in past but forgot. Would you mind to change your comment to answer so I can accept it. Thanks
    – MYaseen208
    Nov 28, 2013 at 11:56

1 Answer 1

12

The easiest way to get exactly what it sounds like you're asking for (without knowing exactly how you plan to use this information) is to use dput:

dput(names(df))
# c("x", "y")

By extension, without fussing with paste:

x <- capture.output(dput(names(df)))
x
# [1] "c(\"x\", \"y\")"
cat(x)
# c("x", "y")

Although @Jilber deleted his answer, you can use shQuote to go from what he had started with to the output of "x" above:

paste("c(", paste(shQuote(names(df)), collapse = ", "), ")", sep = "")
# [1] "c(\"x\", \"y\")"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.