Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple columns to a tibble?

Tags:

r

dplyr

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
like image 414
Olivier VR Avatar asked Feb 14 '19 15:02

Olivier VR


1 Answers

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.

like image 78
Spacedman Avatar answered Nov 01 '22 17:11

Spacedman