根据位置、年份和人名对变量进行分组

Grouping variables based on location, year and person name

我想创建列的聚合

A<- c("xyz", "xyz", "xy", "xx","xx", "y")
year<- c(2009,2010,2009,2009,2010,2009)
location<- c('london', 'london', 'paris', 'newyork','mumbai','sydney')
df<- data.frame(A, year, location)

我想创建一个名为“yearsofexperience”的变量,它将总结一个人在给定地点度过的总年数。

   A     year         location  yearsofexperience
   xyz  2009          london     2
   xyz  2010          london     2
   xy   2009          paris      1
   xx   2009          newyork    1
   xx   2010          mumbai     1
   y    2009          sydeny     1

有人可以帮忙吗?

您可以使用 n_distinct() 来计算每个人和地点组合的唯一年份。这应该适合你:

library(dplyr)
df %>% group_by(A, location) %>% mutate(yoe = n_distinct(year))

# Source: local data frame [6 x 4]
# Groups: A, location [5]

#       A  year location   yoe
#  <fctr> <dbl>   <fctr> <int>
#1    xyz  2009   london     2
#2    xyz  2010   london     2
#3     xy  2009    paris     1
#4     xx  2009  newyork     1
#5     xx  2010   mumbai     1
#6      y  2009   sydney     1

也可以使用data.table语法,对应函数为uniqueN():

library(data.table)
setDT(df)[, yoe := uniqueN(year), .(A, location)]

使用 dplyr 您可以使用 group_bymutate 来获取您在问题中列出的输出

library(dplyr)
df %>% 
  group_by(A, location) %>% 
  mutate(yearsofexperience = n()) %>% 
  ungroup()

如果您想折叠给定 Alocation 的条目,您可以使用 summarise 代替 mutate 语句。这将删除 year 变量。

df %>% 
  group_by(A, location) %>% 
  summarise(yearsofexperience = n()) %>% 
  ungroup()

如果有人感兴趣,这里有一个使用 data.table 的(可以说更简洁的)解决方案,在大数据集上应该会快得多。

require(data.table)
setDT(df)[, yearsofexperience := .N, by = .(A, location)]
df
     A year location yearsofexperience
1: xyz 2009   london                 2
2: xyz 2010   london                 2
3:  xy 2009    paris                 1
4:  xx 2009  newyork                 1
5:  xx 2010   mumbai                 1
6:   y 2009   sydney                 1

我们可以使用 ave 来自 base R

df$yearsofexperience <- with(df, ave(year, location, A, FUN = length))
df
#     A year location yearsofexperience
#1 xyz 2009   london                 2
#2 xyz 2010   london                 2
#3  xy 2009    paris                 1
#4  xx 2009  newyork                 1
#5  xx 2010   mumbai                 1
#6   y 2009   sydney                 1

如果这是基于 lengthunique 个元素

df$yearsofexperience <- with(df, ave(year, location, A, FUN = function(x) length(unique(x))))