How to pivot wider a data frame of two columns

Hi,

I'm stacked with this task. It seems pretty easy, but I don't know how to fix it. I share with you my dataset.

> dput(head(H.D, n =20))
structure(list(Bovine = c("BIN", "BIN", "BIN", "BIN", "BIN", 
"BIN", "BIN", "BIN", "BIN", "BTA", "BTA", "BTA", "BTA", "BTA", 
"BTA", "BTA", "BTA", "CAQ", "CAQ", "CAQ"), H.D = c(1.04, 1.015, 
1.03, 1.051, 1.04, 1.057, 1.078, 1.062, 1.02, 1.024, 1.054, 1.038, 
1.023, 1.019, 1.014, 1.016, 1.041, 1.014, 1.027, 1.024)), row.names = c(NA, 
20L), class = "data.frame")

I want to built a data frame as follows:

BIN             BTA         CAQ
values      values     values
values      values     values
values      values     values
...         ...        ...

I was running this code, but I got this error:

new.df <- df %>%
          pivot_longer(names_to = "Bovine", values_to = "H.D")

Error in `$<-.data.frame`(`*tmp*`, "call_text", value = c("data %>% select(Bovine, H.D) %>% data.frame(t(H.D)) %>% ...",  : 
  replacement has 4 rows, data has 3

Thanks in advance

You input df is a long form data.frame with 2 columns. So you need to use pivot_wider to get your "BIN", "BTA", etc columns

df |> tidyr::pivot_wider(names_from = Bovine, values_from = `H.D`)

with the exact data you provide above you will get a warning as there are a different number of values for each category. But I suspect your real data will be slightly different.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.