我有一个 Dataframe ,看起来像这样:
df <- data.frame(residence_pre = c("house", "apartment", "house"),
residence_during = c("house", "apartment", "house"),
residence_after = c("house", "apartment", "house"),
family_pre = c(1,2,3),
family_during = c(2,2,4),
family_after = c(1,2,4))
字符串
我想用一种看起来像这样的方式来透视它:(这是示例数据。在真实的数据框架中有更多的列,都遵循这种模式)
pivot <- data.frame(obs.number = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
residence = c("house", "house", "house", "apartment", "apartment", "apartment", "house", "house", "house"),
family = c(1, 2, 1, 2, 2, 2, 3, 4, 4),
status = c("pre", "during", "after", "pre", "during", "after", "pre", "during", "after"))
型
4条答案
按热度按时间3bygqnnd1#
在添加
obs.number
之后,我们可以在一个pivot步骤中完成:字符串
5lwkijsr2#
这里有一个方法,你可以尝试
字符串
p3rjfoxz3#
如果数据集的其余部分确实使用了相同的列模式,那么类似这样的方法可能会起作用-我们首先将数据集按列分成部分(residence,family),分别透视部分,然后将
left_join()
应用于结果tibble列表中,直到purrr::reduce()
。字符串
测试结果:
型
创建于2023-10-28使用reprex v2.0.2
d7v8vwbk4#
考虑基数R到
reshape
两个 * residence * 和 * family * 集合,然后merge
通过 * id * 和 * status * 字段:字符串
Online Demo