Home > Software engineering >  combine vectors into df, and turn vector names into rows of a new column
combine vectors into df, and turn vector names into rows of a new column

Time:11-24

I want to combine N vectors into a data frame that includes a column where the values are the names of the original vectors. For example, say I have these three vectors:

fruits <- c('apple', 'pear', 'banana', 'raspberry')
vehicles <- c('cars', 'bikes', 'buses', 'trains')
weather <- c('sunny', 'windy', 'rainy', 'cloudy', 'cold', 'hot')

I can get halfway to what I want by using enframe from the tidyverse. E.g.

enframe(c(fruits, vehicles, weather), name = "name", value = "value")

# A tibble: 14 × 2
    name value    
   <int> <chr>    
 1     1 apple    
 2     2 pear     
 3     3 banana   
 4     4 raspberry
 5     5 cars     
 6     6 bikes    
 7     7 buses    
 8     8 trains   
 9     9 sunny    
10    10 windy    
11    11 rainy    
12    12 cloudy   
13    13 cold     
14    14 hot     

But what I want now is a new column that contains the names of the three vectors from which the elements come from. E.g.

# A tibble: 14 × 2
    name value    
   <chr> <chr>    
  fruits apple    
  fruits pear     
  fruits banana   
  fruits raspberry
vehicles cars     
vehicles bikes    
vehicles buses    
vehicles trains   
 weather sunny    
 weather windy    
 weather rainy    
 weather cloudy   
 weather cold     
 weather hot     

Does anyone know how I can achieve this?

CodePudding user response:

You can use stack after mget.

stack(mget(c("fruits", "vehicles", "weather")))
#      values      ind
#1      apple   fruits
#2       pear   fruits
#3     banana   fruits
#4  raspberry   fruits
#5       cars vehicles
#6      bikes vehicles
#7      buses vehicles
#8     trains vehicles
#9      sunny  weather
#10     windy  weather
#11     rainy  weather
#12    cloudy  weather
#13      cold  weather
#14       hot  weather
  • Related