问题描述
我正在重塑一个数据框:
I am trying to reshape a dataframe:
目前看起来像这样:
ID | Gender |A1 | A2 | A3 | B1 | B2 | B3
ID_1 | m | 3 | 3 | 3 | 2 | 3 | 2
ID_2 | f | 1 | 1 | 1 | 4 | 4 | 4
我想要的是:
ID | Gender | A1 | A2 | A3
ID_1 | m | 3 | 3 | 3 <- this would be columns A1 - A3 for ID 1
ID_1 | m | 2 | 2 | 2 <- this would be columns B1 - B3 for ID 1
ID_2 | f | 1 | 1 | 1 <- this would be columns A1 - A3 for ID 2
ID_2 | f | 4 | 4 | 4 <- this would be columns B1 - B3 for ID 2
(A1和B1 / A2和B2是相同的变量(关于内容),所以例如:A1和B1将是测试1的结果的两个变量,A2和B2都包含测试2的结果。所以为了评估它,我需要所有Test1的结果在一列,所有的测试2在另一列
我试图解决这个熔化,但它只会熔化数据帧逐个,而不是块(因为我需要保持前2列的方式,只能重新排列最后4列,但是作为三个块)
任何其他想法?谢谢!
(A1 and B1 / A2 and B2 are the same variables (with regard to the content), so for example: A1 and B1 would be both variables for the result of Test 1 and A2 and B2 both contain the result of Test 2. So in order to evaluate it I need all the result of Test1 in one column and all of Test 2 in another column.I tried to solve this with "melt", but it only melts down the dataframe one by one, not as chunks. (since I need to keep the first 2 columns the way they are and only rearrange the last 4 columns, but as chunks of three)Any other ideas? Thanks!
推荐答案
使用的一个班轮从基础R重新整理
reshape(dat, varying = 3:8, idvar = 1:2, direction = 'long', drop=FALSE,
timevar = 'Test')
ID Gender Test Test1 Test2 Test3
ID_1.m.A ID_1 m A A1 A2 A3
ID_2.f.A ID_2 f A A1 A2 A3
ID_1.m.B ID_1 m B B1 B2 B3
ID_2.f.B ID_2 f B B1 B2 B3
这篇关于R重构,通过块重构数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!