通过堆叠列和重复其他列来组织数据框以进行分析 [英] Organise a data frame for analysis by stacking columns and repeating others

查看:14
本文介绍了通过堆叠列和重复其他列来组织数据框以进行分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 ``olddf 获取 newdf.基本上,我想复制和堆叠列 AB以允许列CD````堆叠成一列.抱歉解释不好,本质上,我将 CD 堆叠成一列,需要重复 AB 以解决重复问题,谢谢.

I am trying to get newdf from ``olddf. Basically, I want to duplicate and stack columns AandBto allow for columnsCandD```` 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆