如何在R中转换字符列

时间:2012-10-08 20:36:52

标签: r reshape

使用像这样的数据框

df <- data.frame(Season=c("1992","1993","1993"),
               Team=c("Man Utd.","Blackburn","Blackburn"),
               Player=c("Peter Schmeichel(42)","Tim Flowers(39)","Bobby Mimms(4)"),
               Order = c(1,1,2))

我如何达到这个

   1992  Man Utd. Peter Schmeichel(42)     
   1993 Blackburn      Tim Flowers(39)  Bobby Mimms(4) 

4 个答案:

答案 0 :(得分:3)

这是一个选项:

library(reshape2)
dcast(df,Season+Team~Order,value.var = "Player")

答案 1 :(得分:2)

这是一个解决方案:

library(plyr)
ddply(df, .(Season, Team), summarize, Players = paste(Player, collapse = " "))

#-----
  Season      Team                        Players
1   1992  Man Utd.           Peter Schmeichel(42)
2   1993 Blackburn Tim Flowers(39) Bobby Mimms(4)

答案 2 :(得分:2)

坚持基础R,您可以执行以下操作:

aggregate(list(Player = df$Player), 
          list(Season = df$Season, Team = df$Team), paste)
#   Season      Team                          Player
# 1   1993 Blackburn Tim Flowers(39), Bobby Mimms(4)
# 2   1992  Man Utd.            Peter Schmeichel(42)

更新

从已接受的答案中看到了您想要的输出,请注意使用基础R的reshape()函数也可以这样做:

reshape(df, direction = "wide", idvar=c("Season", "Team"), timevar="Order")
#   Season      Team             Player.1       Player.2
# 1   1992  Man Utd. Peter Schmeichel(42)           <NA>
# 2   1993 Blackburn      Tim Flowers(39) Bobby Mimms(4)

答案 3 :(得分:0)

另一个选择是使用`tidyr

library(tidyr)
spread(df,Order,Player)