# A tibble: 3 × 3 Name Age Enrolled <chr> <dbl> <lgl> 1 Alice 20 TRUE 2 Bob 22 FALSE 3 Charlie 21 TRUE
# add two more columnsstudents %>%add_column(grades =c(89, 98, 92),university =c("Harvard", "MIT", "NYU") )
Output:
# A tibble: 3 × 5 Name Age Enrolled grades university <chr> <dbl> <lgl> <dbl> <chr> 1 Alice 20 TRUE 89 Harvard 2 Bob 22 FALSE 98 MIT 3 Charlie 21 TRUE 92 NYU
Use .before (or .after) to specify the position of the new columns. (The same arguments are also used in mutate() in the same way; and in add_row() to specify new rows’ position.)
students %>%add_column(grades =c(89, 98, 92),university =c("Harvard", "MIT", "NYU"), # add the two columns after the 'Name' column.after ="Name" )
Output:
# A tibble: 3 × 5 Name grades university Age Enrolled <chr> <dbl> <chr> <dbl> <lgl> 1 Alice 89 Harvard 20 TRUE 2 Bob 98 MIT 22 FALSE 3 Charlie 92 NYU 21 TRUE
You can use this function to combine two tibbles by columns. Note that you can’t overwrite existing columns, and the columns to be added together must have the same row number.
more_features <-tibble(grades =c(89, 98, 92),university =c("Harvard", "MIT", "NYU")) # insert the `more_features` tibble before the 'Name' columnstudents %>%add_column(more_features, .after ="Name")
Output:
# A tibble: 3 × 5 Name grades university Age Enrolled <chr> <dbl> <chr> <dbl> <lgl> 1 Alice 89 Harvard 20 TRUE 2 Bob 98 MIT 22 FALSE 3 Charlie 92 NYU 21 TRUE