首页 > 解决方案 > 使用 dplyr 从单列数据创建和更新数据框

问题描述

我正在使用 R 创建数据集。我在下面提供了一个信息列表,作为单列 xls 提供。我想将此列表更改为数据集(data.frame?),其列名如下所示。我将获得更多包含新列表的 xls 文档,但是虽然列名将始终保持不变,但它们下面的行将随着新数据的添加而变化(始终按以下顺序)。自动化数据导入并将新信息添加到现有数据集(假设它们是多个 xls 文件)的最简单方法是什么?

Name:
Jon Doe
City:
Chicago
State:
IL
Zip:
60007
Angler Class:
Male
Fish Information:
Date Caught:
09/13/1999
Time:
8 pm
Length:
12.00 Inches
Weight:
Not Specified
Girth:
Not Specified
Fish Depth:
9 Feet
Lake Depth:
Not Specified
Kept/Release:
Released
Species:
Bass
Weather Information:
Sky:
Clear
Wind Direction:
South West
Wind Speed:
Strong
Lake Information:
Lake Name:
Pewaukee Lake
County:
Waukesha
State:
Wisconsin
Lake Bottom:
Junk Weeds
Structure:
Not Specified
Lure Information:
Lure Name:
Rapala
Primary Color:
Black
Secondary Color:
Not Specified
Presentation:
Casting

我想要的输出:

姓名 城市 状态 压缩 被捕日期 时间 物种 诱饵名称 湖名 状态
乔恩·多伊 芝加哥 伊利诺伊州 60007 1999 年 9 月 13 日 晚上 8 点 低音 拉帕拉 皮沃基湖 威斯康星州
简·多伊 匹兹堡 功放 15237 1999 年 8 月 15 日 下午 6 点 低音 夹具 圣克莱尔湖 密歇根州

*请注意,列表中使用了两次“状态”来表示垂钓者状态和湖泊状态。我想在我的桌子上将其捕获为“angle_state”/“lake_state”。

标签: rdataframedplyrtidyverse

解决方案


这是一个 tidyverse 方法,它采用列表,如果它有一个冒号,则将其标记为“标题”,填写标题名称,按每个标题排序以保留响应(如果可用),然后更宽地旋转到所需的格式:

library(tidyverse)
my_data %>%

    # label headers and fill down
    rowid_to_column("row")  %>%
    mutate(header = str_detect(data, ":"),
           header_name = if_else(header, data, NA_character_),
           response    = if_else(header, NA_character_, data)) %>%
    fill(header_name) %>%
    
    # get best row for each header (ie non-NA if it exists)
    group_by(header_name) %>%
    arrange(response) %>%
    slice(1) %>% 
    ungroup() %>%
    
    # rearrange to original order and spread wider
    arrange(row) %>%
    select(-c(row:header)) %>% 
    pivot_wider(names_from = header_name, values_from = response)

结果

# A tibble: 1 x 29
  `Name:` `City:` `State:` `Zip:` `Angler Class:` `Fish Informatio… `Date Caught:` `Time:` `Length:`  `Weight:`   `Girth:`   `Fish Depth:` `Lake Depth:` `Kept/Release:` `Species:` `Weather Informat… `Sky:` `Wind Direction… `Wind Speed:` `Lake Informati… `Lake Name:` `County:` `Lake Bottom:` `Structure:` `Lure Informati… `Lure Name:`
  <chr>   <chr>   <chr>    <chr>  <chr>           <chr>             <chr>          <chr>   <chr>      <chr>       <chr>      <chr>         <chr>         <chr>           <chr>      <chr>              <chr>  <chr>            <chr>         <chr>            <chr>        <chr>     <chr>          <chr>        <chr>            <chr>       
1 Jon Doe Chicago IL       60007  Male            NA                09/13/1999     8 pm    12.00 Inc… Not Specif… Not Speci… 9 Feet        Not Specified Released        Bass       NA                 Clear  South West       Strong        NA               Pewaukee La… Waukesha  Junk Weeds     Not Specifi… NA               Rapala      
# … with 3 more variables: Primary Color: <chr>, Secondary Color: <chr>, Presentation: <chr>

您应该能够利用此数据和dplyr::row_bind其他数据的输出来扩大您的表格以包含多个人。


推荐阅读