I want to add multiple empty columns to a tibble. The names of the new columns are stored in 'columnsToAdd'
> columnsToAdd
[1] "column1" "column2" "column3" "column4" "column5"
When I run the following code lines, ...
library(dplyr)
someTibble <- tibble(name = paste("Name", 1:10))
columnsToAdd <- paste("column", 1:30, sep = "")
someTibble %>%
tibble::add_column(columnsToAdd = NA)
... I get this result, ...
# A tibble: 10 x 2
name columnsToAdd
<chr> <lgl>
1 Name 1 NA
2 Name 2 NA
3 Name 3 NA
4 Name 4 NA
5 Name 5 NA
6 Name 6 NA
7 Name 7 NA
8 Name 8 NA
9 Name 9 NA
10 Name 10 NA
... instead, I want to get the following result:
# A tibble: 10 x 6
name column1 column2 column3 column4 column5
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Name 1 NA NA NA NA NA
2 Name 2 NA NA NA NA NA
3 Name 3 NA NA NA NA NA
4 Name 4 NA NA NA NA NA
5 Name 5 NA NA NA NA NA
6 Name 6 NA NA NA NA NA
7 Name 7 NA NA NA NA NA
8 Name 8 NA NA NA NA NA
9 Name 9 NA NA NA NA NA
10 Name 10 NA NA NA NA NA
Just create them as columns. This works for base data frames and data.table tables:
Eg:
> someTibble <- tibble(name = paste("Name", 1:10))
> columnsToAdd <- paste("column", 1:3,sep="")
That gives me one column:
> head(someTibble)
# A tibble: 6 x 1
name
<chr>
1 Name 1
2 Name 2
3 Name 3
4 Name 4
5 Name 5
6 Name 6
Then I do:
> someTibble[,columnsToAdd]=NA
and magically the columns appear:
> head(someTibble)
# A tibble: 6 x 4
name column1 column2 column3
<chr> <lgl> <lgl> <lgl>
1 Name 1 NA NA NA
2 Name 2 NA NA NA
3 Name 3 NA NA NA
4 Name 4 NA NA NA
5 Name 5 NA NA NA
6 Name 6 NA NA NA
Note this is not really magic, it is standard base R behaviour since from before R was born.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With