Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make a named list (e.g. using setNames), followed by as.data.frame:

df <- as.data.frame(setNames(as.list(vector2), vector1))

Note that it needs to be a list: when converting a named vector into a data.frame, R puts values into separate rows instead of columns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading