R 是否有使用apply优化此功能的代码? 加载库 从英格兰联赛数据中提取利物浦数据

R 是否有使用apply优化此功能的代码? 加载库 从英格兰联赛数据中提取利物浦数据,r,apply,data-manipulation,R,Apply,Data Manipulation,我知道如何使用apply函数是stackoverflow中一个非常无聊和常见的问题,但是我不能用apply函数解决这个问题。 有什么方法吗?:) 因此,您希望将字符类型的一列重新编码为整数列。其中一个选项是简单地使用一个ifelse,它是矢量化的,在这种情况下使用起来很方便,您不想使用apply,它意味着在矩阵中循环: Liverpool.home$points <- with(Liverpool.home, ifelse(result == "H", 3,

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

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

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
利物浦主场$pointsdplyr 来自
dplyr
的函数
case\u when
(“if和else if的向量化集合”)相当于SQL case when语句。我们需要在
变异中使用
$

library(dplyr)
Liverpool.home %>% 
  mutate(points = case_when(.$result == 'H' ~ 3,
                            .$result == 'D' ~ 1,
                            TRUE ~ 0))
sqldf SQL中的语句来自
sqldf

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)
试试这个

transform(Liverpool.home, points = 3 * (result == "H") + (result == "D"))
library(dplyr)
Liverpool.home %>% 
  mutate(points = case_when(.$result == 'H' ~ 3,
                            .$result == 'D' ~ 1,
                            TRUE ~ 0))
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
transform(Liverpool.home, points = 3 * (result == "H") + (result == "D"))