【问题标题】:Is there any code using apply to optimize this?是否有任何代码使用 apply 来优化它?
【发布时间】:2016-09-06 14:02:53
【问题描述】:

加载库

library(engsoccerdata)
library(dplyr)
library(lubridate)

从英格兰联赛数据中提取利物浦数据

england$Date <- ymd(england$Date)
Liverpool.home <- england %>% filter(Date > '2001-08-01', home == 'Liverpool')
Liverpool.away <- england %>% filter(Date > '2001-08-01', visitor == 'Liverpool')

制作可变点

Liverpool.home$points = 0

for(i in 1:nrow(Liverpool.home)){

  if(Liverpool.home[i,]$result == 'H'){
    Liverpool.home[i,]$points = 3
  }
  else if(Liverpool.home[i,]$result == 'D'){
    Liverpool.home[i,]$points = 1
  }

}

我知道如何使用 apply 函数是 stackoverflow 中非常无聊和常见的问题,但是我无法使用 apply 函数解决这个问题。 有什么方法吗? :)

【问题讨论】:

    标签: r apply data-manipulation


    【解决方案1】:

    dplyr

    来自dplyr 的函数case_when(“一组if 和else ifs”)相当于SQL CASE WHEN 语句。我们需要在mutate.中使用.$

    library(dplyr)
    Liverpool.home %>% 
      mutate(points = case_when(.$result == 'H' ~ 3,
                                .$result == 'D' ~ 1,
                                TRUE ~ 0))
    

    sqldf

    来自sqldf的SQL中的CASE WHEN语句:

    library(sqldf)
    df <- sqldf('SELECT result, 
                         CASE WHEN result = "H" THEN 3 
                              WHEN result = "D" THEN 1
                              ELSE 0
                         END AS points
                 FROM [Liverpool.home]')
    head(df)
    

    输出:

      result points
    1      A      0
    2      A      0
    3      H      3
    4      D      1
    5      H      3
    6      H      3
    

    【讨论】:

      【解决方案2】:

      因此,您想将字符类型的列重新编码为整数列。一种选择是简单地使用ifelse,它是矢量化的,在这种情况下使用起来很方便,你不想使用apply,它意味着循环matrix

      Liverpool.home$points <- with(Liverpool.home, ifelse(result == "H", 3, 
                                                           ifelse(result == "D", 1, 0)))
      
      head(Liverpool.home[c("result", "points")])
      
      #  result points
      #1      A      0
      #2      A      0
      #3      H      3
      #4      D      1
      #5      H      3
      #6      H      3
      

      【讨论】:

        【解决方案3】:

        试试这个。

        transform(Liverpool.home, points = 3 * (result == "H") + (result == "D"))
        

        【讨论】:

          猜你喜欢
          • 2013-07-02
          • 1970-01-01
          • 1970-01-01
          • 2014-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多