【问题标题】:Reshape wide format (87 items) into long format 4 variables将宽格式(87 项)重塑为长格式 4 个变量
【发布时间】:2019-10-11 09:30:26
【问题描述】:

我有一个宽格式的数据框(四个变量,从 1 到 7 分级),重复 87 个项目。我的数据框是这样的

主题|第 1 项的变量 1|第 1 项的变量 2|第 1 项的变量 3|第 1 项的变量 4

直到我们到达第 87 项的变量 1|第 87 项的变量 2|第 87 项的变量 3|第 87 项的变量 4

目标:

主题变量1变量2变量3变量3变量4

1

1

1

1(87 项)

欣赏任何代码示例..

【问题讨论】:

  • 我绝对是新手

标签: r reshape reshape2 tidy


【解决方案1】:

此解决方案使用 tidyr 包中的“pivot_longer”和“pivot_wider”。 如果您以前使用过 tidyr 或 tidyverse,我建议您检查您是否拥有 tidyr 版本 1.0.0,或者只是重新安装 tidyr...

所以首先我建议你有机会时看看这篇文章,它会提供很多帮助: https://tidyr.tidyverse.org/articles/pivot.html

工作流程非常简单。 首先,我们需要使您的非常宽的数据变长。 其次,我们需要将变量列和项目列分开 然后最后我们可以只用可变列再次旋转宽度

# Create dummy data
x <- tibble(
        var = c('Variable 1 for item 1', 'Variable 2 for item 1', 
                'Variable 3 for item 1', 'Variable 4 for item 1', 
                'Variable 1 for item 2', 'Variable 2 for item 2', 
                'Variable 3 for item 2', 'Variable 4 for item 2'),
        results = c(runif(8))) %>% 
        mutate(subject = row_number())

# Pivot the table wider to replicate the description. 
# I could have written it this way, but I thought it might 
# take longer ... 
x_wide <- x %>% 
        pivot_wider(names_from = var, 
                    values_from = results)


# This is the actual part you care about
x_long <- x_wide %>%
# So first we need to make the table longer, so that 
# we can manipulate the column names into something workable
        pivot_longer(cols = starts_with('Variable'), 
                     names_to = 'var', 
                     values_to = 'val') %>%
# Next we need to separate the column name into variable and item
        separate(var, into = c('variable', 'item'), 
                 sep = 'for') %>% 
# This is just cleaning up the item and variable columns
        mutate(item = str_remove(item, 'item'), 
               item = str_trim(item, side = 'both'), 
               variable = str_trim(variable, side = 'both')
               ) %>% 
# lastly we pivot wide again but this time only on the variable
        pivot_wider(names_from = variable, 
                    values_from = val)

希望这会有所帮助! 我不得不对数据的样子做出很多假设。如果我猜错了,很高兴跟进。

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2017-03-01
    • 2021-10-26
    • 2013-03-18
    相关资源
    最近更新 更多