在R中转换数据结构

在R中转换数据结构,r,R,我看到的数据结构是: head(data) ID Gender Location Generation Question Response 1 2 Male South America Generation X Q0. Vote in the upcoming election? 0: No 2 2 Male South America Generation X Q1.

我看到的数据结构是:

head(data)
  ID Gender      Location   Generation                           Question Response
1  2   Male South America Generation X Q0. Vote in the upcoming election?    0: No
2  2   Male South America Generation X                     Q1. Pulse Rate    0: No
3  2   Male South America Generation X                     Q2. Metabolism    0: No
4  2   Male South America Generation X                  Q3.Blood Pressure   1: Yes
5  2   Male South America Generation X                    Q4. Temperature    0: No
6  2   Male South America Generation X         Q5. Galvanic Skin Response   1: Yes
此数据框中的列标题如下所示:

> colnames(data)
[1] "ID"         "Gender"     "Location"   "Generation" "Question"   "Response" 
问题
作为标题包含所问问题,
回答
。我希望看到的是:

> colnames(final_data)
 [1] "ID"                                 "Gender"                            
 [3] "Location"                           "Generation"                        
 [5] "Q0. Vote in the upcoming election?" "Q1. Pulse Rate"                    
 [7] "Q134. Good Job Skills"              "Q135. Sense of Humor"              
 [9] "Q136. Intelligence"                 "Q137.Can Play Jazz"                
[11] "Q138.Likes the Beatles"             "Q139. Snobbiness"                  
[13] "Q140.Ability to lift heavy objects" "Q141.Grace under pressure"         
[15] "Q142.Grace on the dance floor"      "Q143.Likes animals"                
[17] "Q144.Makes good coffee"             "Q145.Eats all his/her vegetables"  
[19] "Q2. Metabolism"                     "Q3.Blood Pressure"                 
[21] "Q4. Temperature"                    "Q5. Galvanic Skin Response"        
[23] "Q6. Breathing"                      "Q7. Perspiration"                  
[25] "Q8.Pupil Dilation"                  "Q9. Adrenaline Production" 
目前,我的数据记录在一行中的每个ID的属性。本质上,这意味着每一行只有一个唯一ID的属性


我看到了另一个问题,但没能理解。有人能帮忙吗?

我不知道你到底想让数据看起来怎么样。 我的猜测是,你希望数据 ID、性别、位置、生成为前4列,然后将问题转换为列名,并将其答案作为相应列下的值。 要做到这一点,您只需在R中的
restrape2
包中使用
melt
dcast
函数即可

x=melt(data,id=c("ID","Gender","Location","Generation"))
#this will melt the data frame telling R that these 4 variables are your primary keys
final_data=dcast(x, ID + Gender + Location + Generation ~ Question, value.var="Response")

我想这会奏效的

我看不出问题所在。你想达到什么目标?期望的结果是什么?你有一个可复制的例子吗?非常感谢,我想投上一票(无意中点击了向下箭头)。现在我没有足够的分数来改变。非常感谢阿尤斯,我会记住这个把戏的。真的很有帮助只是好奇…从这个阶段开始,我如何才能让数据看起来像它是什么样子?你将再次熔化这个新数据,并给id=c(“id”,“性别”,“位置”,“生成”),它将恢复数据的原样