此解决方案使用 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)
希望这会有所帮助!
我不得不对数据的样子做出很多假设。如果我猜错了,很高兴跟进。