基于现有列和分组在R数据帧中创建新列

时间:2011-08-03 17:08:39

标签: r data-manipulation

我有一个游戏足球队信息的数据框df(MATCHID),这些初始值

 TEAMID Venue LEAGUEPOS MATCHID
 WHU     A         5       1
 COV     H        12       1
 EVE     H        15       2
 MNU     A         2       2
 ARS     A         3       3
 LEI     H         4       3

我希望为每个游戏创建一行,以便最终看起来像

MATCHID HomeTeam AwayTeam HomePos AwayPos
   1       COV      WHU     12      5      etc.

所以我想创建一些新列,删除其他列并删除重复的行。

我在第一阶段尝试时遇到了麻烦

df $ HomeTeam< - df $ TEAMID [df $ Venue ==“H”]

因为这会产生

 TEAMID Venue LEAGUEPOS MATCHID HomeTeam
   WHU     A         5       1      COV
   COV     H        12       1      EVE
   EVE     H        15       2      LEI
   MNU     A         2       2      STH
   ARS     A         3       3      TOT
   LEI     H         4       3      WIM

HomeTeam只显示Venue = H

的每条记录的顺序TEAMID

2 个答案:

答案 0 :(得分:5)

这可以使用函数reshape轻松实现,该函数是基础R的一部分。

# READ DATA
mydf = read.table(textConnection("
TEAMID Venue LEAGUEPOS MATCHID
 WHU     A         5       1
 COV     H        12       1
 EVE     H        15       2
 MNU     A         2       2
 ARS     A         3       3
 LEI     H         4       3"), 
 sep = "", header = T, colClasses = rep('character', 4))

# RESHAPE DATA
reshape(mydf, idvar = 'MATCHID', timevar = 'Venue', direction = 'wide')

这是产生的输出

  MATCHID TEAMID.A LEAGUEPOS.A TEAMID.H LEAGUEPOS.H
1       1      WHU           5      COV          12
3       2      MNU           2      EVE          15
5       3      ARS           3      LEI           4

注意:另一种方法是使用cast包中的meltreshape函数。

require(reshape)
mydf_m = melt(mydf, id = c('MATCHID', 'Venue'))
cast(mydf_m, MATCHID ~ Venue + variable)

答案 1 :(得分:1)

基地R中的

reshape()做了你想要的,如果有点笨拙的话。这是您的数据:

con <- textConnection(" TEAMID Venue LEAGUEPOS MATCHID
 WHU     A         5       1
 COV     H        12       1
 EVE     H        15       2
 MNU     A         2       2
 ARS     A         3       3
 LEI     H         4       3
")
dat <- read.table(con, header = TRUE, stringsAsFactors = FALSE)
close(con)

我们reshape()这个,按请求的顺序获取列,并更新列名称:

newdat <- reshape(dat, direction = "wide", timevar = "Venue", idvar = "MATCHID")
## reorder
newdat <- newdat[, c(1,4,2,5,3)]
names(newdat) <- c("MatchID","HomeTeam","AwayTeam","HomePos","AwayPos")

这给了我们:

> newdat
  MatchID HomeTeam AwayTeam HomePos AwayPos
1       1      COV      WHU      12       5
3       2      EVE      MNU      15       2
5       3      LEI      ARS       4       3