r - 基于两列过滤数据框
问题描述
我有一个df
像这样的数据框
food color popular
apple red no
pear green no
banana yellow yes
apple red yes
如何仅基于两列(食物和颜色)获得不重复的行?
预期结果:
food color popular
pear green no
banana yellow yes
我试过了:
df %>% distinct(food, color, .keep_all = TRUE)
但这并没有给我预期的结果
解决方案
library(dplyr)
# Create test data
df = tibble(
food=c("apple", "pear", "bananna", "apple"),
color=c("red", "green", "yellow", "red"),
popular=c(F, F, T, T)
)
df %>%
# Make a group for each combination of food and colour
group_by(food, color) %>%
# Then delete any group with more than 1 element
# (since they are duplicates)
filter(n() == 1) %>%
ungroup()
# A tibble: 2 × 3
food color popular
<chr> <chr> <lgl>
1 pear green FALSE
2 bananna yellow TRUE
推荐阅读
- plugins - 无法加载插件类型 - 更新
- pandas - 数据框中非空值的百分比
- typescript - 如何在使用具有默认参数的泛型时修复“类型'BaseCtor'不可分配给类型'T'”
- python-3.x - 合并 2 个具有不同列名的数据帧,显示共同元素,以及数据帧之间的差异
- gnuplot - Gnuplot - 如何使用两个数组和文件中的数据进行 splot
- java - 将字符串 imageData 返回到我的 jsp 上的图像
- c++ - 使用 `std::size_t` 的 ADL
- glsl - 如何正确使用顶点着色器来变形 PShape
- java - 如何从 http 请求创建 Flux
- ionic-framework - 处理 Ionic 4/Firebase 断开连接的最佳方法是什么