使用mutate使用R中每个组的第一个值创建一个新列 [英] Using mutate to create a new column with the first value of each group in R

查看:138
本文介绍了使用mutate使用R中每个组的第一个值创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事Sabermetric研究项目,整日忙于尝试在数据框中创建一个新列,以显示给定游戏的起始投手。本质上,如果我使用下面的示例,则具有 a和 b的数据,但是我不知道如何为 a的每个唯一值创建 c作为 b的第一个值'。这应该很容易,但是我刚刚开始学习R。

I'm currently working on a Sabermetric research project and I've been stuck all day trying to create a new column in a data frame that displays the starting pitcher for a given game. Essentially, if I use the sample below, I have data for 'a' and 'b', but I can't figure out how to create 'c' to be the first value of 'b' for each unique value of 'a'. This should be easy, but I just started learning R.

    a   b   c
1   1   1   1
2   1   2   1
3   1   3   1
4   1   4   1
5   1   5   1
6   1   6   1
7   2   7   7
8   2   8   7
9   2   1   7
10  2   2   7
11  2   3   7
12  2   4   7
13  3   5   5
14  3   6   5
15  3   7   5

到目前为止,我已使用 mutate group_by 得出
sample<-sample%>%group_by(a)%> ;%mutate(c = first(b))
但这只是使'c'的 every 值成为第一个'b'的第一个值。因此,在上面的示例中,我当前的代码使'c'的每个值都等于1。
我缺少了什么,有什么建议吗?

So far I've used mutate and group_by to come up with sample <- sample %>% group_by(a) %>% mutate(c = first(b)) But this just makes every value of 'c' the first value of the first 'b'. So in the sample above, my current code makes every value of 'c' equal to 1. I'm missing something, any suggestions?

推荐答案

使用库 dplyr ,您可以执行以下操作:

Using library dplyr, you can do something like this:

library(dplyr)
df %>% group_by(a) %>% mutate(c = b[1])

输出如下:

Source: local data frame [15 x 3]
Groups: a [3]

       a     b     c
   (int) (int) (int)
1      1     1     1
2      1     2     1
3      1     3     1
4      1     4     1
5      1     5     1
6      1     6     1
7      2     7     7
8      2     8     7
9      2     1     7
10     2     2     7
11     2     3     7
12     2     4     7
13     3     5     5
14     3     6     5
15     3     7     5

将列更改为以下注释中提到的类型并且运行代码会产生所需的输出:

Changing columns to the types mentioned below in comments and running code produces desired output:

df$b <- as.factor(df$b)
df$a <- as.character(df$a)
str(df)
'data.frame':   15 obs. of  3 variables:
 $ a: chr  "1" "1" "1" "1" ...
 $ b: Factor w/ 8 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 1 2 ...
 $ c: int  1 1 1 1 1 1 7 7 7 7 ...

df %>% group_by(a) %>% mutate(c = b[1])
Source: local data frame [15 x 3]
Groups: a [3]

       a      b      c
   (chr) (fctr) (fctr)
1      1      1      1
2      1      2      1
3      1      3      1
4      1      4      1
5      1      5      1
6      1      6      1
7      2      7      7
8      2      8      7
9      2      1      7
10     2      2      7
11     2      3      7
12     2      4      7
13     3      5      5
14     3      6      5
15     3      7      5

这篇关于使用mutate使用R中每个组的第一个值创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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