R dataframe/lapply():删除包含特定字符串的列中具有特定值的行,同时保留其他所有内容?

问题描述 投票:0回答:2

我有 16 个数据帧,我正在尝试质量检查并删除 R 中质量较差的行。我已经知道 lapply() 并将它用于更简单的争吵问题,以便一次将相同的东西应用于我的所有数据帧,但无论出于何种原因我目前有精神障碍。

每个individual数据框的格式是这样的,其中每隔一列包含一个“标志”列。标志列包含值字符串。如果字符串中的任何值是 4,我想从数据框中过滤掉这些行。

head(df)

timestamp    wind_speed_max wind_speed_max_flags   wind_speed_mean
1            UTC meters per second                  NAN meters per second
2    data logger   Airmar WS-200WX                  NAN   Airmar WS-200WX
3 6/2/2015 15:46               7.6              1 1 4 1              5.12
4 6/2/2015 16:01               7.2              1 1 1 1              5.16
5 6/2/2015 16:16               8.1              1 1 1 1              5.97
6 6/2/2015 16:31               8.5              1 1 1 1             5.909
  wind_speed_mean_flags wind_direction_mean wind_direction_mean_flags
1                   NAN             degrees                       NAN
2                   NAN     Airmar WS-200WX                       NAN
3               1 1 1 1               57.14                   1 2 1 2
4               1 1 1 1               61.64                   1 2 1 4
5               1 1 1 1                  68                   1 2 1 2
6               4 1 1 1               73.14                   1 2 1 2

我知道我可以尝试用 grep("flags") 来获取列名,我也认为我可以使用类似的 grep 方法来过滤掉包含 4 的字符串?也许使用一些布尔运算符。但是我正在努力将所有这些拼凑在一起以保留其余数据,并且理想情况下同时对所有 16 个数据帧执行此操作

lapply(df_list, function(x) <insert code that can filter out flags with 4s for each x dataframe>) 

r lapply data-cleaning data-wrangling grepl
2个回答
1
投票

让我们从编写代码来过滤一个数据框开始——我们将查看名称中包含“flags”和“4”的 grep 的列。然后我们将使用

rowSums
来计算每行中 4 的数量,只保留 4 count == 0 的行。

# count the number of 4s in each row of "flag" cols of `df`
count_4 = df[grepl("flags", names(df))] |>
  sapply(grepl, pattern = "4") |>
  rowSums(na.rm = TRUE)

放入

lapply
:

modified_data_list = lapply(data_list, function(df) {
  count_4 = df[grepl("flags", names(df))] |>
    sapply(grepl, pattern = "4") |>
    rowSums(na.rm = TRUE)
  df[count_4 == 0, ]
})

0
投票

tidyverse

library(dplyr)
library(purrr)
library(stringr)
map(data_list,  ~.x %>%
              filter(!if_any(contains("flags"), ~ str_detect(.x, "4"))))
© www.soinside.com 2019 - 2024. All rights reserved.