在特定时间之前创建不同的值列

问题描述 投票:0回答:1

我有一个问题,如何计算直到某个时间点的唯一值。例如,我想知道一个人到那时为止居住了多少个独特的位置。

 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)

我想创建一个名为unique的变量,其中要考虑到那个时间点他住过多少不同的地方。我尝试了以下方法。有什么建议吗?

  library(dplyr) 
   df %>% group_by(person, location) %>% arrange(Created,.by_group = TRUE) %>% mutate (unique=distinct (location))

  unique <- c(1, 2, 2, 3,1,1)
r dplyr data.table plyr tidyr
1个回答
0
投票

一种方法是每match使用person

library(dplyr)
df %>% group_by(person) %>% mutate(unique = match(location, unique(location)))

#  created person location unique
#    <dbl> <fct>  <fct>     <int>
#1    2009 A      London        1
#2    2010 A      Geneva        2
#3    2010 A      London        1
#4    2011 A      New York      3
#5    2012 B      London        1
#6    2011 B      London        1
© www.soinside.com 2019 - 2024. All rights reserved.