我有一个具有以下结构的数据框:
x <- data.frame("id" = c(1,1,1,2,2), "v1" = c("NB","MTA","MTA","RN","CANC"), "v2" = c(1,2,2,10,9))
我要做的是在此数据框中基于“ v1”列的值创建一个新列。该列应检查每个唯一ID,“ v1”列是否具有“ NB”或“ RN”值。如果是这样,则该列应具有该值。结果应该是:
> result <- data.frame("id" = c(1,1,1,2,2), "v1" = c("NB","MTA","MTA","RN","CANC"), "v2" = c(1,2,2,10,9), "v3" = c("NB","NB","NB","RN","RN"))
> result
id v1 v2 v3
1 1 NB 1 NB
2 1 MTA 2 NB
3 1 MTA 2 NB
4 2 RN 10 RN
5 2 CANC 9 RN
我一直在dplyr中使用group-by,但是却无法正常工作
答案 0 :(得分:0)
您可以使用ave
查找每个组中是否存在NB
或RN
,例如:
x$V3 <- ave(x$v1, x$id, FUN=function(x) c("NB", "RN")[min(match(x, c("NB", "RN")), na.rm=TRUE)])
x
# id v1 v2 V3
#1 1 NB 1 NB
#2 1 MTA 2 NB
#3 1 MTA 2 NB
#4 2 RN 10 RN
#5 2 CANC 9 RN
或者使用新函数,如果未找到任何内容,则返回NA
:
f <- (function(y) {
force(y)
function(x) {
y[min(c(3, match(x, y)), na.rm=TRUE)]
}
})(c("NB", "RN", NA))
x$V3 <- ave(x$v1, x$id, FUN=f)
答案 1 :(得分:0)
使用<div>
{{ test.time }}
<ng-template *ngTemplateOutlet="tmplInputTime; context: { value:test}"></ng-template>
</div>
<ng-template #tmplInputTime let-value="value">
<input type="time" [(ngModel)]="value.time" > <!-- value not changing on input-->
</ng-template>
,您可以执行以下操作:
dplyr
或者:
df %>%
group_by(id) %>%
mutate(v3 = if_else(any(v1 == "NB"), "NB", "RN"))
id v1 v2 v3
<dbl> <fct> <dbl> <chr>
1 1 NB 1 NB
2 1 MTA 2 NB
3 1 MTA 2 NB
4 2 RN 10 RN
5 2 CANC 9 RN