通过将两个不同命名的列折叠为一个来熔化data.frame

时间:2016-03-10 21:45:32

标签: r

我想转此:

   game_date  team_id  opponent_id team_away team_outcome   opponent_outcome
1 2016-03-09    a           b     FALSE          loss              win

  structure(list(game_date = "2016-03-09", team_id = "a", opponent_id = "b", 
team_away = FALSE, team_outcome = "loss", opponent_outcome = "win"), .Names = c("game_date", 
"team_id", "opponent_id", "team_away", "team_outcome", "opponent_outcome"
), class = "data.frame", row.names = "1")

进入这个:

game_date     team outcome   away
2016-03-09     a     loss   FALSE
2016-03-09     b     win    TRUE

我无法确定使用reshape执行此操作的最佳方法。我试过了

dcast(x, team_id + opponent_id ~ team_outcome)
melt(x, id.vars = c("team_id", "opponent_id"), measure.vars = c("team_outcome", "team_away") 

2 个答案:

答案 0 :(得分:1)

通过重塑你可以做到:

y=melt(x,id=c("game_date","team_id","opponent_id","team_away")
    ,measure.vars=c("team_outcome","opponent_outcome"))

获得:

   game_date team_id opponent_id team_away         variable value
1 2016-03-09       a           b     FALSE     team_outcome  loss
2 2016-03-09       a           b     FALSE opponent_outcome   win

然后这些来获得您想要的列:

y$team=ifelse(y$variable == "team_outcome","a","b")
y$away=ifelse(y$variable == "team_outcome" & y$team_away == FALSE,"yes","no")
z=y[,c("game_date","team","value","away")]

答案 1 :(得分:0)

在基地R找到了一种方法,但仍然很好奇,如果有融化/重塑/ dcast方式。

all_outcomes<-data.frame(c(x$team_id, x$opponent_id), 
c(x$team_outcome, x$opponent_outcome), 
c(x$team_away, !x$team_away), 
c(x$game_date))