连接日期格式时将data.frame宽转换为长
在R(或其他语言)中,我想将上层数据帧转换为下层数据帧。 我该怎么做? 事先谢谢你连接日期格式时将data.frame宽转换为长,r,matrix,frame,R,Matrix,Frame,在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 好吧,看起来您正试图在同一个问题中执行多个操作:合并日期列、
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
好吧,看起来您正试图在同一个问题中执行多个操作:合并日期列、融化数据、一些colnames转换和排序 这将提供您的预期输出:
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来实现这一点。这里有一个只使用两个包的解决方案,
dplyr
和tidyr
首先,您的数据集:
df <- dplyr::data_frame(
year =2016,
month = c("07", "08"),
income = c(50,30),
expense = c(15, 75)
)
输出包含您需要的所有信息(但我们将在最后一步中进行清理)
注意:我想我使用了三个库,包括管道操作符
%>%
的magrittr
。但是,由于管道操作器是有史以来最好的东西,我经常忘记计算magrittr
由于您非常喜欢管道操作符:-),您可能会着迷于发现“管道分配”操作符。不用写df%%…
你只需写df%%…
就行了!虽然我倾向于不使用它,因为我喜欢看到赋值%
之间的差异。恐怕我会混淆管道和管道赋值操作符,因为它们与眼睛非常相似。好的,您已经熟悉了。我同意,你所说的部分正确,可能不是一个理想的答案。
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
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