将向量合并为 df,并将向量名称转换为新列的行

combine vectors into df, and turn vector names into rows of a new column

我想将 N 个向量组合成一个数据框,其中包含一列,其中的值是原始向量的名称。例如,假设我有这三个向量:

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

我可以通过使用 tidyverse 中的 enframe 获得我想要的一半。例如

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     

但我现在想要的是一个新列,其中包含元素所来自的三个向量的名称。例如

# 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     

有谁知道我怎样才能做到这一点?

您可以在 mget 之后使用 stack

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