简体   繁体   中英

Dataframe from vector values

I have vectors such as

porcentages1<-c(19.63081,29.87414,32.12955,18.36550)
porcentages2<-c(19.58452,29.94807,32.19970,18.26772)

Where each index of the vector represents a percentage of an item (for example the first index represents the percentage of dogs and the second the percentage of cats)

I want to create a data frame such as this one

Any ideas on how?

One way could be:

library(dplyr)
library(tibble)

as_tibble(rbind(porcentages1, porcentages2)) %>% 
  rename(Dogs = V1, Cats = V2, Sharks = V3, Turtles = V4)
  Dogs  Cats Sharks Turtles
  <dbl> <dbl>  <dbl>   <dbl>
1  19.6  29.9   32.1    18.4
2  19.6  29.9   32.2    18.3

Here is an option using data.table :

library(data.table)

output <- setnames(as.data.table(transpose(list(porcentages1, porcentages2))),
                   c("Dogs", "Cats", "Sharks", "Turtles"))

Output

output

       Dogs     Cats   Sharks  Turtles
1: 19.63081 29.87414 32.12955 18.36550
2: 19.58452 29.94807 32.19970 18.26772

Or another option using tidyverse :

library(tidyverse)

map_dfc(purrr::transpose(list(porcentages1, porcentages2)), ~ unlist(tibble(.))) %>%
  set_names(c("Dogs", "Cats", "Sharks", "Turtles"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM