Sahib
Sahib

Reputation: 160

How to add quotations to all columns?

I am trying to automate the addition of quotations to all elements in a dataframe, without have to explicitly provide the col name. Is there a way that can be done.

I tried:

x<-iris

for (i in colnames(x)){
  paste0('x$',i)<-paste0('"x$',i,'"')
}

However get the following error:

Error in paste0("x$", i) <- paste0(""x$", i, """) : target of assignment expands to non-language object*

I can do it for single columns, but require for the whole dataframe.

print(x$Species<- paste0('"', x$Species, '"'))

Upvotes: 0

Views: 323

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270248

Using the built-in data frame BOD we have the following. Note that it does not overwrite the input but rather produces a new output.

replace(BOD, TRUE, lapply(BOD, shQuote, type = "cmd"))

giving:

  Time demand
1  "1"  "8.3"
2  "2" "10.3"
3  "3"   "19"
4  "4"   "16"
5  "5" "15.6"
6  "7" "19.8"

Upvotes: 0

B. Christian Kamgang
B. Christian Kamgang

Reputation: 6529

Here is one solution:

x <- iris

x[] <- lapply(x, sprintf, fmt = '"%s"')


  Sepal.Length Sepal.Width Petal.Length Petal.Width  Species
1        "5.1"       "3.5"        "1.4"       "0.2" "setosa"
2        "4.9"         "3"        "1.4"       "0.2" "setosa"
3        "4.7"       "3.2"        "1.3"       "0.2" "setosa"
4        "4.6"       "3.1"        "1.5"       "0.2" "setosa"
5          "5"       "3.6"        "1.4"       "0.2" "setosa"
6        "5.4"       "3.9"        "1.7"       "0.4" "setosa"
...

Upvotes: 1

Related Questions