Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column names of a data.frame separated with comma

Tags:

r

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")
like image 232
MYaseen208 Avatar asked Feb 15 '23 12:02

MYaseen208


1 Answers

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\")"
like image 164
A5C1D2H2I1M1N2O1R2T1 Avatar answered Feb 17 '23 11:02

A5C1D2H2I1M1N2O1R2T1