I have a dataframe with a single row. Pairs of columns go together, where one holds the name and the other has the value. So I want to extract name & column combination from the 1-row format onto stacked format, having one column for names and a second for values. I'm trying pivot_longer
but somehow can't get it done.
Data
library(tidyverse)
df <-
tribble(~ var_1, ~ var_1_value, ~ var_2, ~ var_2_value, ~ var_3, ~ var_3_value,
"height", 200, "weight", 400, "length", 1000)
> df
## var_1 var_1_value var_2 var_2_value var_3 var_3_value
## <chr> <dbl> <chr> <dbl> <chr> <dbl>
## 1 height 200 weight 400 length 1000
Desired Output
var_name var_value
<chr> <dbl>
1 height 200
2 weight 400
3 length 1000
What I've tried
df %>%
pivot_longer(cols = everything(),
names_to = ".value",
names_pattern = "var_[0-9]_(.*)")
## value
## <dbl>
## 1 200
## 2 400
## 3 1000
I know that this is a fairly elementary problem, but I can't figure out how to solve this, nor did I find a similar answered problem. Thanks!