提前致谢。我有以下数据:
df <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3),
neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"))
我想生成一个新列,该列提供每个人在面板进展时所经过的邻域的累积计数。像这样:
df2 <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3),
neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"),
moved=c(0,0,0,0,0,0,1,1,0,0,1,2)
)
再次感谢。
答案 0 :(得分:5)
我们可以按'人'使用分组,然后通过match
使用unique
值创建'移动'来获取索引并减去1。
df %>%
group_by(person) %>%
mutate(moved = match(neighborhood, unique(neighborhood))-1)
# person neighborhood moved
# <dbl> <fctr> <dbl>
#1 1 A 0
#2 1 A 0
#3 1 A 0
#4 1 A 0
#5 2 B 0
#6 2 B 0
#7 2 C 1
#8 2 C 1
#9 3 D 0
#10 3 D 0
#11 3 E 1
#12 3 F 2
或使用factor
并将levels
指定为'邻域'中的unique
值,强制为'整数'并减去1。
df %>%
group_by(person) %>%
mutate(moved = as.integer(factor(neighborhood, levels = unique(neighborhood)))-1)
# person neighborhood moved
# <dbl> <fctr> <dbl>
#1 1 A 0
#2 1 A 0
#3 1 A 0
#4 1 A 0
#5 2 B 0
#6 2 B 0
#7 2 C 1
#8 2 C 1
#9 3 D 0
#10 3 D 0
#11 3 E 1
#12 3 F 2
答案 1 :(得分:4)
使用rleid
包中的frank
或data.table
函数也可轻松实现此目的:
library(data.table)
# with 'rleid'
setDT(df)[, moved := rleid(neighborhood)-1, by = person]
# with 'frank'
setDT(df)[, moved := frank(neighborhood, ties.method='dense')-1, by = person]
结果:
> df
person neighborhood moved
1: 1 A 0
2: 1 A 0
3: 1 A 0
4: 1 A 0
5: 2 B 0
6: 2 B 0
7: 2 C 1
8: 2 C 1
9: 3 D 0
10: 3 D 0
11: 3 E 1
12: 3 F 2
使用dplyr
,您可以使用dense_rank
功能:
library(dplyr)
df %>%
group_by(person) %>%
mutate(moved = dense_rank(neighborhood)-1)
答案 2 :(得分:0)
这也可以使用dplyr
的窗口函数来实现。这是代码:
library(dplyr)
my.df <- tbl_df(df)
my.df %>%
# Per person
group_by(person) %>%
# sort by neighborhood
arrange(neighborhood) %>%
# if the neighborhood has changed compared to the row before
mutate(moved = (neighborhood != lag(neighborhood))) %>%
# turn NAs (first rows) into FALSE
mutate(moved = ifelse(is.na(moved), FALSE, moved)) %>%
# use cumulative sum of the logical column to get number of moves
mutate(no_moves = cumsum(moved))