简体   繁体   English

新列说明观察首次发生的时间

[英]New column that tells when observation first occurred

I am trying to create a new column 'First Appearance that tells me when the observation first occurred using the tidyverse package.我正在尝试创建一个新列“第一次出现”,它告诉我使用 tidyverse package 首次发生观察的时间。

For Example: If I have例如:如果我有

Year Observation观察
2000 2000 A一个
2000 2000 B
2001 2001年 A一个
2001 2001年 C C

I would like the following outcome.我想要以下结果。

Year Observation观察 First Appearance首次亮相
2000 2000 A一个 2000 2000
2000 2000 B 2000 2000
2001 2001年 A一个 2000 2000
2001 2001年 C C 2001 2001年
library(dplyr)

df %>% 
  group_by(Observation) %>% 
  mutate(FirstObservation = min(Year)) %>% 
  ungroup()

Output Output

   Year Observation FirstObservation
  <int> <chr>                  <int>
1  2000 A                       2000
2  2000 B                       2000
3  2001 A                       2000
4  2001 C                       2001

Data数据

df <- structure(list(Year = c(2000L, 2000L, 2001L, 2001L), Observation = c("A", 
"B", "A", "C")), class = "data.frame", row.names = c(NA, -4L))

I know it is asked about tidyverse , still, I include a variant using data.table我知道有人问过tidyverse ,但我仍然包含一个使用data.table的变体

library(data.table)
setDT(df)
df[,FistAppearance:= min(Year), Observation]
df
       Year Observation FistAppearance
1: 2000           A           2000
2: 2000           B           2000
3: 2001           A           2000
4: 2001           C           2001

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从不同列中的另一个观察值中减去一个观察值,并将特定值添加到结果中以在 R 的第一列中创建一个新观察值 - Subtract an observation from another in different column and add a specific value to the result to create a new observation in the first column in R 如何不使用第一次观察作为 R 中的列名? - How to not use first observation as column names in R? 如何找到与条件匹配的列的第一个观察值 - How to find the first observation of a column that matches a condition 如何创建一个变量来告诉我其他变量中的哪一个是第一个对于一个观察没有缺失值的变量? - How do I create a variable that tells me which of a number of other variables is the first one to not have a missing value for one observation? 创建列,告诉前两列之间的数字来源 - Create column which tells source of number between the first two columns 如何创建一个对另一个变量进行首次观察的新变量? - How to create a new variable that takes the first observation of a different variable? 在R中生成一个新变量,其中第n个观察值取决于另一个列的第n-1次观察 - Generating a new variable in R where the nth observation depends on the n-1th observation of another column 从先前的观察中选择日期,并将其输入到R中的新列中 - Select date from a previous observation and input it into a new column in R R-根据条件观察结果创建新列并将其应用于主df - R - Creating a new column based on a conditional observation and applying it to the master df 根据另一列的先前观察值创建新变量 - Create new variable based on prior observation value from another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM