在连接日期格式时将 data.frame 宽转换为长

Convert data.frame wide to long while concatenating date formats

在 R(或其他语言)中,我想将上层数据框转换为下层数据框。 我怎样才能做到这一点? 预先谢谢你。

year month income expense
2016 07 50 15
2016 08 30 75


month income_expense
1 2016-07             50
2 2016-07            -15
3 2016-08             30
4 2016-08            -75

好吧,您似乎正试图在同一个问题中执行多项操作:合并日期列、融化数据、一些列名转换和排序

这将给出您预期的输出:

library(tidyr); library(reshape2); library(dplyr)
df %>% unite("date", c(year, month)) %>% 
  mutate(expense=-expense) %>% melt(value.name="income_expense") %>% 
  select(-variable) %>% arrange(date)
####      date income_expense
#### 1 2016_07             50
#### 2 2016_07            -15
#### 3 2016_08             30
#### 4 2016_08            -75

我在这里使用了三个不同的库,以提高代码的可读性。不过,也许可以用 base R 来做到这一点。

这是一个只使用两个包的解决方案,dplyrtidyr

首先,您的数据集:

df <- dplyr::data_frame(
  year =2016,
  month = c("07", "08"),
  income = c(50,30), 
  expense = c(15, 75)
)

mutate() 函数在 dplyr creates/edits 个单独的变量中。 tidyr 中的 gather() 函数将按照您指定的方式将多个 variables/columns 组合在一起。

df <- df %>% 
  dplyr::mutate(
    month = paste0(year, "-", month)
  ) %>% 
  tidyr::gather(
    key = direction, #your name for the new column containing classification 'key' 
    value = income_expense, #your name for the new column containing values
    income:expense #which columns you're acting on
  ) %>% 
  dplyr::mutate(income_expense =  
    ifelse(direction=='expense', -income_expense, income_expense)  
  )

输出包含您需要的所有信息(但我们会在最后一步清理它)

   > df
# A tibble: 4 × 4
   year   month direction income_expense
  <dbl>   <chr>     <chr>          <dbl>
1  2016 2016-07    income             50
2  2016 2016-08    income             30
3  2016 2016-07   expense            -15
4  2016 2016-08   expense            -75

最后,我们 select() 删除不需要的列,然后对其进行排列,以便 df 以与您在问题中描述的顺序相同的顺序显示行。

df <- df %>% 
  dplyr::select(-year, -direction) %>% 
  dplyr::arrange(month)
> df
# A tibble: 4 × 2
    month income_expense
    <chr>          <dbl>
1 2016-07             50
2 2016-07            -15
3 2016-08             30
4 2016-08            -75

注意:我想我正在使用三个库,包括用于管道运算符 %>%magrittr。但是,由于管道运算符是有史以来最好的东西,我经常忘记数 magrittr