首页 > 解决方案 > 转换数据框以便能够过滤值

问题描述

我想将以下数据帧转换为一个新的数据帧,我可以在其中过滤这样的系数:

例子:

样本 %>% 过滤器(年龄 == “18-30”)

结果应给出年龄“18-30”的系数。

我不想使用匹配方法!我已经尝试过pivot_longer(),但它没有产生我想要的数据框结构。

sample <- data.frame (GLM_Coefficient  = c(0.6, 1, 0.4, 0.2, 0, 3 ,1 ,2,1),
                  Category = c("France", "UK", "USA", "18-30", "31-50", "51-70", "70+", "100-170", "171+"),
                  Type = c("Country", "Country", "Country", "Age", "Age", "Age", "Age", "Height", "Height")
)



  GLM_Coefficient Category    Type
1             0.6   France Country
2             1.0       UK Country
3             0.4      USA Country
4             0.2    18-30     Age
5             0.0    31-50     Age
6             3.0    51-70     Age
7             1.0      70+     Age
8             2.0  100-170  Height
9             1.0     171+  Height

标签: rfilterdplyr

解决方案


如果您只需要系数,则必须过滤两者TypeCategory然后选择GLM_coefficient

sample %>% filter(Type == "Age", Category == "18-30") %>% select(GLM_Coefficient)

如果您不希望它成为 tibble,则需要添加pull

sample %>% filter(Type == "Age", Category == "18-30") %>% select(GLM_Coefficient) %>% pull()

推荐阅读