【问题标题】:R: Extract data from previous observation of same factor level in dataframeR:从数据框中相同因子水平的先前观察中提取数据
【发布时间】:2021-04-10 10:38:01
【问题描述】:

我正在尝试在数据框中创建列,以显示给定足球队的 form。即各自的足球队在上一场比赛中是赢、平还是输。

将下面的数据框视为一系列足球比赛。在第一场比赛中,利物浦击败了切尔西。我想做的是用这个结果来展示利物浦在下一场比赛中的状态。 所以,当利物浦对阵莱斯特城时,我希望 HomeForm 说“W”(代表胜利),而 AwayForm 也说“W”,因为莱斯特城也赢得了上一场比赛。

问题用一句话概括,就是我不知道有什么函数可以告诉 R 识别一个特定因子水平的前一个(或两个)观察值(Liverpool for例如),然后从之前的一个(或两个)观察中提取我想要的数据。

HomeTeam <- c("Liverpool", "ManCity", "ManUnited", "Tottenham", "Arsenal", "Leicester", "Chelsea", "Leeds", "Liverpool", "ManCity", "ManUnited", "Tottenham", "Arsenal", "Leicester", "Chelsea","Liverpool", "ManCity", "ManUnited", "Tottenham", "Arsenal", "Leicester", "Chelsea", "Leeds", "Liverpool", "ManCity", "ManUnited", "Tottenham", "Arsenal", "Leicester", "Chelsea")
AwayTeam <- c("Chelsea", "Tottenham", "Arsenal", "ManUnited", "Leicester", "ManCity", "Leeds", "Chelsea", "Leicester", "Liverpool", "Arsenal", "ManUnited", "Tottenham", "ManCity", "Liverpool","Chelsea", "Tottenham", "Arsenal", "ManUnited", "Leicester", "ManCity", "Leeds", "Chelsea", "Leicester", "Liverpool", "Arsenal", "ManUnited", "Tottenham", "ManCity", "Liverpool")
Result <- c("H","H","D","A","H","A","H","D","H","A","A","H","D","A","A")

data <- data.frame(HomeTeam,AwayTeam,Result)

data$HomeForm <- 0
data$AwayForm <- 0

【问题讨论】:

    标签: r function dataframe extract factors


    【解决方案1】:

    好的,所以这段代码 1) 获取您的数据帧 2) 将其更改为长格式 3) 滞后于结果列,从而为您提供以前的格式,并且 4) 返回宽格式。希望这会有所帮助。

    teams <- c("Liver", "Man", "United", "Totten")
    Result <- c("Home","Draw", "Away")
    data <- data.frame("Home" = sample(teams, 100, replace = T),
                       "Away" = sample(teams, 100, replace = T),
                       "Result" = sample(Result, 100, replace = T))
            
    data <- data[-which(data$Home == data$Away),]
    
    
    data %>%
    mutate("indexofgames" = 1:n()) %>%
    pivot_longer(., c("Home","Away")) %>%
    mutate("Result" = ifelse(Result == name, "Win", ifelse(Result == "Draw", "Draw", "Loss"))) %>%
    group_by(value) %>%
    arrange(indexofgames) %>%
    mutate("previousform" = lag(Result)) %>%
    pivot_wider(.,id_cols = indexofgames,names_from = c("name"),values_from = c("value", "previousform","Result"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多