在 R 中的行之间执行计算 [英] Performing calculations between rows in R

查看:15
本文介绍了在 R 中的行之间执行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何跨(或在?)行之间进行计算.我试过查这个,但显然我的 Google-Fu 今天不强大,因为我没有找到正确的搜索词.

I’m trying to figure out how to make a calculation across (or between?) rows. I’ve tried looking this up but clearly my Google-Fu is not strong today, because I’m just not finding the right search terms.

这是我要处理的数据类型的超级简化示例:

Here is a super simplified example of the type of data I’m trying to deal with:

mydf <- data.frame(pair = rep(1,2), 
                   participant = c("PartX", "PartY"), 
                   goalsAtt = c(6, 3), 
                   goalsScr = c(2, 3))

我们有关于参与者尝试了多少目标"以及他们实际得分多少的数据,假设我想知道他们的防守"能力.现在基本上我想要做的是 mutate() 两个新列,称为...让我们说 savedmissed,其中 saved 将是对方参与者尝试的目标减去他们的进球数,而 missed 将只是对方参与者的进球数.所以很明显,参与者 X 会节​​省 0 并错过 3,参与者 Y 将节省 4 并错过 2.

We have data on how many "goals" a participant attempted and how many they actually scored, and lets say I want to know about their "defensive" ability. Now essentially what I want to do is mutate() two new columns called… let’s say saved and missed, where saved would be the goals attempted by the opposite participant minus the goals scored by them, and missed would just be goals scored by the opposite participant. So obviously participant X would have saved 0 and missed 3, and participant Y will have saved 4 and missed 2.

现在显然这是一个愚蠢的简单示例,我将处理 6 种不同的目标"类型和 2.5k 对,但我只是对从哪里开始有一个心理障碍.

Now obviously this is a stupid simple example, and I’ll have like 6 different "goal" types to deal with and 2.5k pairs to go through, but I’m just having a mental block about where to start with this.

这里是业余程序员,赞赏 Tidyverse 风格的解决方案.

Amateur coder here, and Tidyverse style solutions are appreciated.

推荐答案

好的,让我们假设 pair 只能用于 2 个团队.这是一个 tidyverse 解决方案,我们首先为组内的位置设置一个索引号,然后减去保存的目标.与错过的目标类似.

OK, so let's assume that pair can only be for 2 teams. Here's a tidyverse solution where we first set an index number for position within a group and then subtract for goals saved. Something similar for goals missed.

library(tidyverse)
mydf %>% 
  group_by(pair) %>% 
  mutate(id = row_number()) %>% 
  mutate(goalsSaved = if_else(id == 1,
                              lead(goalsAtt) - lead(goalsScr),
                              lag(goalsAtt) - lag(goalsScr))) %>% 
  mutate(goalsMissed = if_else(id == 1,
                               lead(goalsScr),
                               lag(goalsScr)))

# A tibble: 2 x 7
# Groups:   pair [1]
   pair participant goalsAtt goalsScr    id goalsSaved goalsMissed
   <dbl> <fct>          <dbl>    <dbl> <int>      <dbl>       <dbl>
 1     1 PartX              6        2     1          0           3
 2     1 PartY              3        3     2          4           2

这篇关于在 R 中的行之间执行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆