[英]using case_when() and filter() to subset a dataframe based on values in one column and levels in another column in R
I want to filter (extract rows from) a dataframe based on values from one column while making sure all rows with the same level as the one I extracted are also extracted.我想根据一列中的值过滤(从中提取行)数据帧,同时确保所有与我提取的行具有相同级别的行也被提取。 Example:例子:
condition<- rep(c("c1", "c2", "c3", "c4"), times = 4)
levelled <- c(rep("a",times = 4), rep("b", times = 4), rep("c", times = 4), rep("d", times = 4))
direction <- c(rep("up", times=10), rep("down", times = 1), rep("up", times = 5))
df <- data.frame(condition, levelled, direction)
This results in this dataframe:这导致此数据框:
condition levelled direction
1 c1 a up
2 c2 a up
3 c3 a up
4 c4 a up
5 c1 b up
6 c2 b up
7 c3 b up
8 c4 b up
9 c1 c up
10 c2 c up
11 c3 c down
12 c4 c up
13 c1 d up
14 c2 d up
15 c3 d up
16 c4 d up
I am only interested in direction == "down"
, but I want to extract all rows that have the same level in the levelled
column.我只关心direction == "down"
,但我想提取具有在同级别的所有行levelled
列。 So my desired output df is this:所以我想要的输出 df 是这样的:
desired_output
condition levelled direction
9 c1 c up
10 c2 c up
11 c3 c down
12 c4 c up
In my desired_output
dataframe, I extracted the row with direction == down
but also the other 3 rows that have the same level in the levelled
column.在我的desired_output
数据desired_output
,我提取了direction == down
行,以及在levelled
列中具有相同级别的其他 3 行。 I think I should try something like this, but I don't know what to write on the right hand side of the tilde sign:我想我应该尝试这样的事情,但我不知道在波浪号的右侧写什么:
desired_output <- df %>% fiter(
case_when(
direction == "up" ~ #??
)
)
你想要这样的东西吗?
df <- df %>% group_by(levelled) %>% filter(any(direction == "down"))
You can use -您可以使用 -
subset(df, levelled %in% levelled[direction == 'down'])
# condition levelled direction
#9 c1 c up
#10 c2 c up
#11 c3 c down
#12 c4 c up
In dplyr
you can write this as -在dplyr
您可以将其写为 -
library(dplyr)
df %>% filter(levelled %in% levelled[direction == 'down'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.