'How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values. Here is my reproduceable example:
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
Now I want to convert these two vector into a wide format dataframe:
# A tibble: 1 x 5
Reply Reshare Like Share Search
<dbl> <dbl> <dbl> <dbl> <dbl>
1 2 1 0 4 3
I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?
Solution 1:[1]
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
df <- data.frame(vector1, vector2)
df |> tidyr::pivot_wider(names_from = vector1, values_from = vector2)
#> # A tibble: 1 × 5
#> Reply Reshare Like Share Search
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2 1 0 4 3
Created on 2022-02-08 by the reprex package (v2.0.1)
Solution 2:[2]
Yet another solution, based on dplyr::bind_rows:
library(dplyr)
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
names(vector2) <- vector1
bind_rows(vector2)
#> # A tibble: 1 × 5
#> Reply Reshare Like Share Search
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2 1 0 4 3
Solution 3:[3]
We can use map_dfc and set_names
library(purrr)
set_names(map_dfc(vector2, ~.x), vector1)
# A tibble: 1 × 5
Reply Reshare Like Share Search
<dbl> <dbl> <dbl> <dbl> <dbl>
1 2 1 0 4 3
Solution 4:[4]
Another possible solution:
library(dplyr)
data.frame(rbind(vector1, vector2)) %>%
`colnames<-`(.[1, ]) %>%
.[-1, ] %>%
`rownames<-`(NULL)
Reply Reshare Like Share Search
1 2 1 0 4 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Grzegorz Sapijaszko |
| Solution 2 | PaulS |
| Solution 3 | GuedesBF |
| Solution 4 | AndrewGB |
