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?
CodePudding user response:
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
CodePudding user response:
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"))