R 如何将带分隔符的字符串转换为表格格式?

R 如何将带分隔符的字符串转换为表格格式?,r,R,我的字符串是这样的: 2 cups - Desiccated Coconut, 2.5 cups - Maida, 1.25 cup - Butter, 1/2 tsp - Baking soda, 1.25 cup - Powdered Sugar, 1/2 tsp - Baking powder, 2-3 drops - Vanilla essence 我想要以下格式的输出: 这里有一个解决方案,您只需要最终为变量指定正确的名称。 下次,请证明您尝试了一些东西或进行了更多的调查。您需要使用

我的字符串是这样的:

2 cups - Desiccated Coconut, 2.5 cups - Maida, 1.25 cup - Butter, 1/2 tsp - Baking soda, 1.25 cup - Powdered Sugar, 1/2 tsp - Baking powder, 2-3 drops - Vanilla essence
我想要以下格式的输出:


这里有一个解决方案,您只需要最终为变量指定正确的名称。 下次,请证明您尝试了一些东西或进行了更多的调查。您需要使用package
stringr
来删除尾随空格和前导空格

txt= c("2 cups - Desiccated Coconut, 2.5 cups - Maida, 1.25 cup - Butter, 1/2 tsp - Baking soda, 1.25 cup - Powdered Sugar, 1/2 tsp - Baking powder, 2-3 drops - Vanilla essence")
splits_per_ingredients = strsplit(txt,c(","))[[1]]
split_per_quantity = sapply(splits_per_ingredients,strsplit," - ")
split_per_dose=t(sapply(split_per_quantity,FUN=function(vec) {c(strsplit(stringr::str_trim(vec[1])," ")[[1]],vec[2])}))
输出:

                              [,1]   [,2]    [,3]                
 2 cups - Desiccated Coconut  "2"    "cups"  "Desiccated Coconut"
  2.5 cups - Maida            "2.5"  "cups"  "Maida"             
  1.25 cup - Butter           "1.25" "cup"   "Butter"            
  1/2 tsp - Baking soda       "1/2"  "tsp"   "Baking soda"       
  1.25 cup - Powdered Sugar   "1.25" "cup"   "Powdered Sugar"    
  1/2 tsp - Baking powder     "1/2"  "tsp"   "Baking powder"     
  2-3 drops - Vanilla essence "2-3"  "drops" "Vanilla essence"

我希望输出为R表。提示:使用逗号拆分,转置,然后使用破折号拆分,然后使用空格拆分,然后添加列名。。。多谢你,伙计:)你救了我一天。
> library(dplyr)
> library(tidyr)
> library(stringr)
> 
> str = '2 cups - Desiccated Coconut, 2.5 cups - Maida, 1.25 cup - Butter, 1/2 tsp - Baking soda, 1.25 cup - Powdered Sugar, 1/2 tsp - Baking powder, 2-3 drops - Vanilla essence'
> 
> df = data.frame(Qty = unlist(strsplit(str, ',')))
> df
                           Qty
1  2 cups - Desiccated Coconut
2             2.5 cups - Maida
3            1.25 cup - Butter
4        1/2 tsp - Baking soda
5    1.25 cup - Powdered Sugar
6      1/2 tsp - Baking powder
7  2-3 drops - Vanilla essence
> 
> df = df %>% separate(Qty, c('Unit', 'Ingredient'), ' - ')
> df
        Unit         Ingredient
1     2 cups Desiccated Coconut
2   2.5 cups              Maida
3   1.25 cup             Butter
4    1/2 tsp        Baking soda
5   1.25 cup     Powdered Sugar
6    1/2 tsp      Baking powder
7  2-3 drops    Vanilla essence
> 
> # remove start & end white spaces (stringr library)
> # or else you can't separate correctly
> df$Unit = str_trim(df$Unit)
> df = df %>% separate(Unit, c('Qty', 'Unit'), ' ')
> df
   Qty  Unit         Ingredient
1    2  cups Desiccated Coconut
2  2.5  cups              Maida
3 1.25   cup             Butter
4  1/2   tsp        Baking soda
5 1.25   cup     Powdered Sugar
6  1/2   tsp      Baking powder
7  2-3 drops    Vanilla essence