我有一個資料框架,它看起來像這樣:
| id | score |
|---|---|
| x | 1 | 3 |
| 3 | y |
我想檢查每個ID在 "分數 "欄中是否有1、2和3。如果有些ID沒有1、2或3,我想把它們保存為一個矢量。
我試圖以某種方式回圈它/在dplyr中寫一個條件,但失敗了:
group_by(id) %>;%
{if(! 1 %in% score | ! 2 %in% score | ! 3 %in% score ) {print(id)}``
uj5u.com熱心網友回復:
通過'id'分組后,過濾創建一個邏輯向量,并包裹all,即如果所有的1、2、3都在'score'中,那么我們否定(!),只過濾那些不符合它的組,得到distinct'id'和pull作為一個vector
library(dplyr)
v1 <- df1 %>%
group_by(id)%>%
filter(! all(c(1。 2。 3) %in% score) ) %> %
ungroup %>%
distinct(id) %> %
pull(id)
輸出
>/span> v1
[1] "z"/span>
注意:print只是在控制臺列印輸出,沒有回傳值。 我們可能需要存盤在一個物件中
在OP的代碼中,帶有
if的條件引數在tidyverse函式之外,并且score在全域環境中不是一個物件,而是資料中的一個列。 我們可以使用.$或.[[>>來提取,但這也會失去分組屬性。 最好是在tidyverse函式中進行,如filter或summarise等。 或者我們可以使用group_modify來做print,基于OP的代碼。
df1 %>%
group_by(id) %>%
group_modify(~ {if(! 1 %in% . x$score | ! 2 %in% .x$score |!3 %in% .x$score ) {
print(.y$id)。
}。
.x})
[1] "z"/span>
# A tibble: 8 x 2
# Groups: id [3]
id得分
<chr> <int>
1 x 1
2 x 2
3 x 3
4 y 1
5 y2
6 y 3
7 z1
8 z 2
data
df1 < -結構(list(id = c("x"/span>。 "x", "x"。 "y", "y", "y"。 "z", "z"),
分數 = c(1L。 2L, 3L, 1L。 2L, 3L, 1L。 2L)),
class = "data.frame", 行。 names = c(NA,)
-8L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329426.html
標籤:
