使用tidyr中的gather函数时保留属性(属性不相同)

12

我有一个数据框需要拆分成两个表以满足 Codd 的第三范式。在简单的情况下,原始数据框大致如下:

library(lubridate)
> (df <- data.frame(hh_id = 1:2,
                   income = c(55000, 94000),
                   bday_01 = ymd(c(20150309, 19890211)),
                   bday_02 = ymd(c(19850911, 20000815)),
                   gender_01 = factor(c("M", "F")),
                   gender_02 = factor(c("F", "F"))))

    hh_id income    bday_01    bday_02 gender_01 gender_02
  1     1  55000 2015-03-09 1985-09-11         M         F
  2     2  94000 1989-02-11 2000-08-15         F         F

当我使用gather函数时,它会警告属性不相同,并且会丢失性别的因素以及bday的lubridate(或者在真实世界的例子中的其他属性)。有没有一个好的tidyr解决方案来避免每列数据类型的损失?

library(tidyr)
> (person <- df %>% 
      select(hh_id, bday_01:gender_02) %>% 
      gather(key, value, -hh_id) %>%
      separate(key, c("key", "per_num"), sep = "_") %>%
      spread(key, value))

     hh_id per_num       bday gender
   1     1      01 1425859200      M
   2     1      02  495244800      F
   3     2      01  603158400      F
   4     2      02  966297600      F

   Warning message:
   attributes are not identical across measure variables; they will be dropped

> lapply(person, class)

  $hh_id
  [1] "integer"

  $per_num
  [1] "character"

  $bday
  [1] "character"

  $gender
  [1] "character"

我可以想象一种方法,即将每组具有相同数据类型的变量分别收集并加入所有表格,但一定有我所缺失的更优雅的解决方案。


我认为目前没有优雅的解决方案 :( 对于这种情况,我认为 gather 可能需要创建一个列表列,以便属性不会丢失。但我认为这将非常缓慢,并且可能会让人感到困惑。 - hadley
@hadley 哦,我明白了。是的,我正在编写一个返回列表结果的函数,但它运行得非常慢。我现在正在寻找更好的解决方案。 - josiekre
3个回答

15
您可以将日期转换为字符,然后在最后将其转换回日期:
(person <- df %>% 
      select(hh_id, bday_01:gender_02) %>% 
      mutate_each(funs(as.character), contains('bday')) %>%
      gather(key, value, -hh_id) %>%
      separate(key, c("key", "per_num"), sep = "_") %>%
      spread(key, value) %>%
      mutate(bday=ymd(bday)))

  hh_id per_num       bday gender
1     1      01 2015-03-09      M
2     1      02 1985-09-11      F
3     2      01 1989-02-11      F
4     2      02 2000-08-15      F

或者,如果您使用Date而不是POSIXct,您可以这样做:

(person <- df %>% 
      select(hh_id, bday_01:gender_02) %>% 
      gather(per_num1, gender, contains('gender'), convert=TRUE) %>%
      gather(per_num2, bday, contains('bday'), convert=TRUE) %>%
      mutate(bday=as.Date(bday)) %>%
      mutate_each(funs(str_extract(., '\\d+')), per_num1, per_num2) %>%
      filter(per_num1 == per_num2) %>%
      rename(per_num=per_num1) %>%
      select(-per_num2))

编辑

您看到的警告信息:

Warning: attributes are not identical across measure variables; they will be dropped

由于收集了性别列,这些列是因素并具有不同级别的向量(请参见str(df))。如果您将性别列转换为字符或将它们的级别与某些内容同步,则会出现此问题。

df <- mutate(df, gender_02 = factor(gender_02, levels=levels(gender_01)))

然后您将会看到,在执行时警告消失了。

person <- df %>% 
        select(hh_id, bday_01:gender_02) %>% 
        gather(key, value, contains('gender'))

这就是我最终做的事情。当我有时间时,我会查看源代码,看看为什么@hadley选择要求相同的属性。一定有一个很好的理由。 - josiekre
@josiekre,我已经更新了我的答案,解释了为什么你会收到那个警告。 - Matthew Plourde

3

您似乎不喜欢我的基础解决方案。让我再次尝试诱惑您

(df <- data.frame(hh_id = 1:2,
                  income = c(55000, 94000),
                  bday_01 = ymd(c(20150309, 19890211)),
                  bday_02 = ymd(c(19850911, 20000815)),
                  gender_01 = factor(c("M", "F")),
                  gender_02 = factor(c("F", "F"))))


reshape(df, idvar = 'hh_id', varying = list(3:4, 5:6), direction = 'long',
        v.names = c('bday','gender'), timevar = 'per_num')

#     hh_id income    per_num       bday gender
# 1.1     1  55000          1 2015-03-09      M
# 2.1     2  94000          1 1989-02-11      F
# 1.2     1  55000          2 1985-09-11      F
# 2.2     2  94000          2 2000-08-15      F

1
这是一个可行的解决方案。我会等一下看看是否有tidyr解决方案可用,因为我需要使用正则表达式来选择不同的列。不幸的是,数据源并不总是以相同的顺序拥有这些列。 - josiekre

1
使用tidyr 1.0.0,可以按以下方式完成:
suppressPackageStartupMessages({
  library(tidyr)
  library(lubridate)
})
df <- data.frame(hh_id = 1:2,
                 income = c(55000, 94000),
                 bday_01 = ymd(c(20150309, 19890211)),
                 bday_02 = ymd(c(19850911, 20000815)),
                 gender_01 = factor(c("M", "F")),
                 gender_02 = factor(c("F", "F")))

pivot_longer(df, -(1:2), names_to = c(".value","per_num"),names_sep = "_" )
#> # A tibble: 4 x 5
#>   hh_id income per_num bday       gender
#>   <int>  <dbl> <chr>   <date>     <fct> 
#> 1     1  55000 01      2015-03-09 M     
#> 2     1  55000 02      1985-09-11 F     
#> 3     2  94000 01      1989-02-11 F     
#> 4     2  94000 02      2000-08-15 F

这篇文章是由reprex package(v0.3.0)于2019年9月14日创建的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接