r语言 - 在连接日期格式时将数据帧宽转换为长



在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

嗯,似乎你正试图在同一个问题上做多个操作:组合日期列,融化你的数据,一些colname转换和排序

这将给出您期望的输出:

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)
)

dplyr中的mutate()函数创建/编辑单个变量。tidyr中的gather()函数将以您指定的方式将多个变量/列组合在一起。

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

最新更新