【问题标题】:Retain select columns and filter the rest based on string保留选择列并根据字符串过滤其余列
【发布时间】:2021-06-01 08:28:46
【问题描述】:

我有一个数据集,我想按特定字符串过滤掉,但除了过滤后还保留两列。

例如。

help <- data.frame(
data  = c(type, 100, 100, 110, 110, 110),
user1 = c("red", "yes", "no", "yes", "no", "yes"),
user2 = c("blue", "yes", "no", "yes", "no", "yes"),
user3 = c("red", "yes", "no", "yes", "no", "yes"),
user4 = c("blue", "yes", "no", "yes", "no", "yes"),
more_data = c(5, 3, 6, 3, 4, 3))

我希望过滤掉第一行数据中颜色为“红色”的用户,同时保留datamore_data

例如,我的最终数据集如下所示:

  data user1 user3 more_data
1  type  red  red   5
2  100   yes  yes   3
3  100    no  no    6
4  110   yes  yes   3
5  110    no  no    4
6  110   yes  yes   3

这是某种过滤器 + grepl 命令,我过滤蓝色的反面吗? filter(help, grepl(!"blue", help)) 但这不起作用。

【问题讨论】:

    标签: r dplyr tidyr grepl


    【解决方案1】:

    我们可以使用selectwhere 来检查any 'red' 值或first 元素中的值

    library(dplyr)
    help %>% 
       select(data, where(~ 'red' %in% first(.)), more_data)
    

    -输出

    #  data user1 user3 more_data
    #1 type   red   red         5
    #2  100   yes   yes         3
    #3  100    no    no         6
    #4  110   yes   yes         3
    #5  110    no    no         4
    #6  110   yes   yes         3
    

    数据

    help <- structure(list(data = c("type", "100", "100", "110", "110", "110"
    ), user1 = c("red", "yes", "no", "yes", "no", "yes"), user2 = c("blue", 
    "yes", "no", "yes", "no", "yes"), user3 = c("red", "yes", "no", 
    "yes", "no", "yes"), user4 = c("blue", "yes", "no", "yes", "no", 
    "yes"), more_data = c(5, 3, 6, 3, 4, 3)), class = "data.frame",
    row.names = c(NA, 
    -6L))
    

    【讨论】:

    • 太棒了。谢谢你,阿克伦。两个后续问题。你能解释一下 where 命令中的波浪号和第一个中的 (.) 吗?这两者如何发挥作用? (.) 只是说第一行吗?
    • @b222 它是 lambda 函数,即动态创建的匿名函数 ~ 是 tidyverse 中 function(x) 的简写选项,默认情况下它是 ..x 在 tidyverse 中。通过调用first(.),它正在提取列的第一个元素,然后我们用red %in%检查它是否等于'red'
    • @b222 您也可以将其传递为help %&gt;% select(data, where(function(x) 'red' %in% first(x)), more_data) 或创建一个函数,即f1 &lt;- function(x) 'red' %in% first(x); help %&gt;% select(data, where(f1), more_data)
    • 这有助于进一步理清问题。谢谢!
    • @b222 我在聊天中
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2021-10-18
    • 2011-01-10
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多