通过堆叠列和重复其他列来组织数据框以进行分析 [英] Organise a data frame for analysis by stacking columns and repeating others
本文介绍了通过堆叠列和重复其他列来组织数据框以进行分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 ``olddf 获取
Anewdf
.基本上,我想复制和堆叠列 和
B以允许列
C和
D````堆叠成一列.抱歉解释不好,本质上,我将 C
和 D
堆叠成一列,需要重复 A
和 B
以解决重复问题,谢谢.
I am trying to get newdf
from ``olddf. Basically, I want to duplicate and stack columns
Aand
Bto allow for columns
Cand
D```` to be stacked in a single column. Sorry for the bad explanation, essentially, I am stacking C
and D
into a single column and need to repeat A
and B
to account for the repetitions, thank you.
olddf <- data.frame('A' = c('Z1','Z2','Z3'),
'B' = c(100, 200, 500),
'C' = c(90, 50, 60),
'D' = c(NA, 50, NA))
newdf <- data.frame('A' = c('Z1','Z2','Z3','Z1','Z2','Z3'),
'B' = c(100, 200, 500, 100, 200, 500),
'CD' = c(90, 50, 60, NA, 50, NA))
推荐答案
tidyverse
解决方案:
olddf |>
pivot_longer(names_to="col", values_to="CD", C:D) |>
arrange(col, A) |>
select(-col)
输出:
# A tibble: 6 x 3
A B CD
<chr> <dbl> <dbl>
1 Z1 100 90
2 Z2 200 50
3 Z3 500 60
4 Z1 100 NA
5 Z2 200 50
6 Z3 500 NA
这篇关于通过堆叠列和重复其他列来组织数据框以进行分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文