我有以下学生的data.frame,他们加入了一个特定的项目
library(data.table)
f.name<-c('a','a','b','b','b','c','c')
year<-c(2014,2015,2013,2014,2015,2015,2016)
grade<-c(9,10,8,9,10,7,8)
f.name<-as.character(f.name)
df.have<-data.frame(f.name,year,grade)
df.have我特别感兴趣的是九年级学生,他们在2014年加入了一个特定的项目。然而,我想区分2014年第一次参加这个项目的9年级学生和即将返回该项目的9年级学生(2013年是8年级学生)。
我创建了一个列来区分在2014年第一次加入这个项目的九年级学生,其方式如下
df.have$new.students<-with(df.have, rowid(f.name) == 1 & year == 2014 & grade == 9)
df.have
f.name year grade new.students
1 a 2014 9 TRUE
2 a 2015 10 FALSE
3 b 2013 8 FALSE
4 b 2014 9 FALSE
5 b 2015 10 FALSE
6 c 2015 7 FALSE
7 c 2016 8 FALSE如何创建另一列来标记返回的学生。2013年上八年级,2014年返校的学生?所以它看起来像这样
f.name year grade new.student returning.students
1 a 2014 9 TRUE FALSE
2 a 2015 10 FALSE FALSE
3 b 2013 8 FALSE FALSE
4 b 2014 9 FALSE TRUE
5 b 2015 10 FALSE FALSE
6 c 2015 7 FALSE FALSE
7 c 2016 8 FALSE FALSE发布于 2018-09-26 20:06:50
可以使用联接查找所需的行。
library(data.table)
setDT(df.have)
# initialize to FALSE
df.have[, rs := FALSE]
# update to TRUE if the desired row is found
df.have[year == 2014 & grade == 9, rs :=
df.have[replace(copy(.SD), c("year", "grade"), list(2013, 8)), on=.(f.name, year, grade), .N, by=.EACHI]$N > 0L
]这可以用by=、any或cumsum来完成,但我认为效率较低:
df.have[, v :=
year == 2014 & grade == 9 & any(year == 2013 & grade == 8)
, by=f.name]
# or...
df.have[order(year), v :=
year == 2014 & grade == 9 & cumsum(year == 2013 & grade == 8)
, by=f.name]发布于 2018-09-26 19:47:22
如果您愿意使用dplyr,可以使用group_by并利用row_number()函数。
library(dplyr)
df.have %>%
group_by(f.name) %>%
mutate(new_student = (grade == 9 & year == 2014 & row_number() == 1),
returning_student = (grade == 9 & year == 2014 & row_number() > 1)) %>%
ungroup()
f.name year grade new_student returning_student
<fct> <dbl> <dbl> <lgl> <lgl>
1 a 2014 9 TRUE FALSE
2 a 2015 10 FALSE FALSE
3 b 2013 8 FALSE FALSE
4 b 2014 9 FALSE TRUE
5 b 2015 10 FALSE FALSE
6 c 2015 7 FALSE FALSE
7 c 2016 8 FALSE FALSE不幸的是,我对data.table不是很熟悉,所以我不能给出一个特定于这个包的答案。
https://stackoverflow.com/questions/52525017
复制相似问题