将第一列的行值转换为R中的列

时间:2016-03-28 03:30:01

标签: r dataframe

我有以下数据框。

Student    Score
Thomas     23.6
Sally      28.1
Chris      27.9
Morrison   32.5
Thomas     30.3
Sally      54.2
Morrison   44.3
Chris      99.2

如何将其转换为

Thomas    Sally    Morrison    Chris
23.6      28.1     32.5        27.9
30.3      54.2     44.3        99.2

注意:它不必具有上述数据框的确切顺序。

我尝试使用reshape2,reshape,dcast,melt,cbind等进行转换。我找不到任何有用的东西。

1 个答案:

答案 0 :(得分:1)

使用dcast包中的reshape2功能。

d1 <- read.table(text="Student    Score
Thomas     23.6
Sally      28.1
Chris      27.9
Morrison   32.5
Thomas     30.3
Sally      54.2
Morrison   44.3
Chris      99.2", head=T, as.is=T)

library(dplyr)

d2 <- d1 %>% group_by(Student) %>% mutate(cn=1:n())

library(reshape2)

dcast(d2, cn~Student, value.var = "Score")
#   cn Chris Morrison Sally Thomas
# 1  1  27.9     32.5  28.1   23.6
# 2  2  99.2     44.3  54.2   30.3