簡體   English   中英

根據位置,年份和人員姓名對變量進行分組

[英]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

有人可以幫忙嗎?

如果有人對此感興趣的話,那就是使用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

使用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()

您可以使用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)]

我們可以從base R使用ave

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

如果這是基於unique元素的length

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM