【问题标题】:Transform dataframe in order to be able to filter values转换数据框以便能够过滤值
【发布时间】:2021-08-12 19:54:19
【问题描述】:

我想将以下数据帧转换为一个新的数据帧,我将能够像这样过滤系数:

例子:

sample %>% filter(Age == "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

【问题讨论】:

  • 您可以只过滤多个列,对吗? filter(sample, Category == "18-30" &amp; Type == "Age")

标签: r filter dplyr


【解决方案1】:

如果您只需要系数,则必须同时过滤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()

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多