【问题标题】:Filter a column to only reveal when there is a value, and remove the others in R (R, dplyr, lubridate)过滤一列以仅在有值时显示,并删除 R 中的其他列(R,dplyr,lubridate)
【发布时间】:2020-02-26 21:02:23
【问题描述】:

我有一个数据框 df,我希望过滤此数据集中的一列,以便仅在有值时显示并删除空白值。

     Name                      Edit                 Folder        Message      Date


     Hello                     T                     Out                       1/5/2020 5:00:00 AM   
     Hi                        T                     Out                       1/5/2020 5:00:02 AM
                               T                     Out                       1/5/2020 5:00:03 AM
     Bye                       T                     Out                       1/5/2020 5:00:04 AM
     See you!                  T                     drafts                    1/5/2020 5:00:05 AM

我希望有这个输出:

     Name                     Edit                 Folder        Message      Date


     Hello                     T                     Out                       1/5/2020 5:00:00 AM   
     Hi                        T                     Out                       1/5/2020 5:00:02 AM
     Bye                       T                     Out                       1/5/2020 5:00:04 AM
     See you!                  T                     drafts                    1/5/2020 5:00:05 AM

因此基本上删除了具有空 Name 值的行。

这就是我的过滤方式:

 df1<-df %>%
 mutate(Date = lubridate::mdy_hms(Date), 
 cond = Edit == "True" & Name !== "" & Folder == "Out" | Folder == "drafts" & Message == "" , 
 grp = cumsum(!cond)) %>%
 filter(cond) %>%
 group_by(grp) %>%
 summarise(starttime = first(Date), 
 endtime = last(Date), 
 duration = difftime(endtime, starttime, units = "secs")) %>%
 select(-grp)

如果 Name 有值,我将如何合并,保留此值并丢弃此代码中的其他值?

输入:

 structure(list(Name = structure(c(3L, 4L, 1L, 2L, 5L), .Label = c("", 
 "Bye", "Hello", "Hi", "See you!"), class = "factor"), Edit = c(TRUE, 
 TRUE, TRUE, TRUE, TRUE), Folder = structure(c(2L, 2L, 2L, 2L, 
 1L), .Label = c("drafts", "Out"), class = "factor"), Message = c(NA, 
 NA, NA, NA, NA), Date = structure(1:5, .Label = c("1/5/2020 5:00:00 AM", 
"1/5/2020 5:00:02 AM", "1/5/2020 5:00:03 AM", "1/5/2020 5:00:04 AM", 
"1/5/2020 5:00:05 AM"), class = "factor")), class = "data.frame", row.names = c(NA, 
 -5L))

【问题讨论】:

  • 这是你想要的吗:dplyr::filter(!is.na(Name))?
  • 嗨,我正在尝试将其合并到我的过滤器中。我只是希望能够删除主题列中的空值或空白值
  • Subject !== "" 更改为 !is.na(Subject)。旁注,它的!= 表示“不等于”而不是!==
  • 你需要df1 %&gt;% filter(Name != "")
  • 我错过了什么吗?示例数据中没有名为“主题”的列,但您正在尝试按它进行过滤

标签: r dplyr tidyverse stringr


【解决方案1】:

base R中,我们可以使用subset

subset(df1, Name != "")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2021-11-30
    相关资源
    最近更新 更多