pssguy
pssguy

Reputation: 3505

How do I cast a character column in R

Using a data frame like this

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))

How do i get to this

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

Upvotes: 2

Views: 5836

Answers (4)

Rfan
Rfan

Reputation: 712

Another option is to use `tidyr

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

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Sticking in base R, you can do the following:

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)

Update

Having seen your desired output from the accepted answer, note that this is also possible using base R's reshape() function:

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)

Upvotes: 2

Chase
Chase

Reputation: 69151

Here's one solution:

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)

Upvotes: 2

joran
joran

Reputation: 173527

Here is one option:

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

Upvotes: 3

Related Questions