0

Is there an easy/simple way of adding a vector of strings as new columns in a data.frame?

Minimal Example

If starting with iris data.frame, and vector vec:

vec <- c("abc", "def", "ghi")

head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          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.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

the desired output would be:

iris$abc <- NA
iris$def <- NA
iris$ghi <- NA

head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species abc def ghi
# 1          5.1         3.5          1.4         0.2  setosa  NA  NA  NA
# 2          4.9         3.0          1.4         0.2  setosa  NA  NA  NA
# 3          4.7         3.2          1.3         0.2  setosa  NA  NA  NA
# 4          4.6         3.1          1.5         0.2  setosa  NA  NA  NA
# 5          5.0         3.6          1.4         0.2  setosa  NA  NA  NA
# 6          5.4         3.9          1.7         0.4  setosa  NA  NA  NA

Note: the above method works, but it isn't very elegant and doesn't scale well when length(vec) is large.

stevec
  • 41,291
  • 27
  • 223
  • 311
  • @Henrik I don't think a loop is any better than the inefficient way I put in the question. I'll change the wording to exclude loops. Please consider reopening – stevec Feb 12 '21 at 00:09
  • @Henrik, actually, my mistake, the end of [this](https://stackoverflow.com/a/18215216/5783745) answer does indeed show how. It's just not as simple to find as Thomas's below. – stevec Feb 12 '21 at 00:12
  • No, the loop is not better. That's why the accepted answer writes: "Or more simply: `df[,namevector] <- NA`" – Henrik Feb 12 '21 at 00:13
  • Thanks @Henrik, I [agree](https://stackoverflow.com/questions/18214395/add-empty-columns-to-a-dataframe-with-specified-names-from-a-vector#comment116976381_18215216) – stevec Feb 12 '21 at 00:14
  • @Henrik just for the record, I tried to retract my reopen vote, but it seems [it's not possible to do so](https://meta.stackoverflow.com/questions/355481/make-it-possible-to-retract-reopen-votes). But I do agree it's a duplicate. – stevec Feb 12 '21 at 14:01
  • 1
    No problem at all! Thanks for the heads-up. Cheers. – Henrik Feb 12 '21 at 14:08

1 Answers1

3

You can try

df[vec] <- NA

where df is iris in your specific example in the post

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81