根据先前的历史记录创建一个新变量 [英] Creating a new variable based on prior history
本文介绍了根据先前的历史记录创建一个新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有需要根据以前的历史记录创建变量的数据
I have data where I need to create a variable based on prior history, for example
created<- c(2009,2010,2010,2011, 2012, 2011)
person <- c(A, A, A, A, B, B)
location<- c('London','Geneva', 'London', 'New York', 'London', 'London')
df <- data.frame (created, person, location)
我想创建一个名为"existing"的变量,该变量考虑到前几年的情况,并查看他/她是否住过该地方,如果该地方是旧的(并且他们住在那里,则给出的值为0).?
I want to create a variable called 'existing' that takes into account the prior years and sees if he/she has lived in that place and gives a value of 0 if the place is old(and they lived there. Any suggestions?
library(dplyr)
df %>% group_by(person) %>% mutate (existing=0)
existing<- c(1, 1, 0, 1, 0,1)
推荐答案
另一个 dplyr
选项可能是:
df %>%
group_by(person, location) %>%
mutate(existing = +(1:n() == 1))
created person location existing
<dbl> <fct> <fct> <int>
1 2009 A London 1
2 2010 A Geneva 1
3 2010 A London 0
4 2011 A New York 1
5 2012 B London 1
6 2011 B London 0
如果需要排序:
df %>%
group_by(person, location) %>%
arrange(created, .by_group = TRUE) %>%
mutate(existing = +(1:n() == 1))
这篇关于根据先前的历史记录创建一个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文