Liz
Liz

Reputation: 35

Why can't I add variables with 1x1 tibbles to a tibble with tibble::add_row?

This is a simple example of what I am trying to do. Why can't I add a row with each variable a 1x1 tibble?

d <- tibble(x = 2, y = 3)
x1 <- tibble(1)
y1 <- tibble(7)

d2 <- d %>%
  tibble::add_row(
    x = x1,
    y = y1
  )

I know the following works but it is not tidy and it just seems like there should be a better way.

d <- tibble(x = 2, y = 3)
x1 <- tibble(1)
y1 <- tibble(7)

d2 <- d %>%
  tibble::add_row(
    x = as.numeric(x1),
    y = as.numeric(y1)
  )

Thanks in advance awesome R people (:

Upvotes: 2

Views: 551

Answers (1)

thelatemail
thelatemail

Reputation: 93813

Upgrading comment to an answer:

You're trying to insert a whole dataset ('tibble' in this instance) into a single cell in your first attempt. You need to select the single column out of the dataset to add as rows.

add_row(d, x = x1[[1]], y = y1[[1]])

Running as.numeric(x1) also converts x1 to a vector in a round-about way, which as you've found, will also work.

You could also go full dplyr and do:

add_row(d, x = pull(x1,1), y = pull(y1,1))

...if you wanted to avoid using the [[ brackets.

Upvotes: 1

Related Questions