我有一個可接受的列值的參考表,good_df如下所示。我想用它來找出以前看不見test_df的值不在可接受的串列中。
library(tidyverse)
good_df <- tribble(
~column, ~value,
"col1", "a",
"col1", "b",
"col1", "c",
"col1", "d",
"col1", "e",
"col2", "A",
"col2", "B",
"col2", "C"
)
set.seed(1)
test_df <- tibble(
col1 = sample(letters[1:3], 4, T),
col2 = c(sample(LETTERS[1:3], 3, T), "D"), # The D is invalid.
col3 = rnorm(4)
)
test_df
#> # A tibble: 4 × 3
#> col1 col2 col3
#> <chr> <chr> <dbl>
#> 1 a A 0.330
#> 2 c C -0.820
#> 3 a C 0.487
#> 4 b D 0.738
由reprex 包(v2.0.1)創建于 2022-06-09
我的想法是使用pivot_longer轉換test_df為匹配的格式,good_df然后用于setdiff查看洗掉有效行后剩余的內容,這一定是無效行。類似于下面的內容,產生expected_output.
long_test_df <- pivot_longer(test_df, "MAGIC HAPPENS HERE")
long_test_df %>%
select(column, value) %>%
setdiff(good_df)
expected_output <- tribble(
~column, ~value,
"col2", "D",
)
我似乎無法pivot_longer按照我的計劃開始作業。也許它不是設計的?我也想過使用 validate 包,但我在檔案中沒有看到任何關于在創建規則時明確列出允許或禁止值的內容,除非我錯過了什么。
當然,在實踐中,我的資料集中還有更多可接受的列/值對和更多列需要驗證。
我對我的方法的替代方案以及存盤允許的列值集的替代形式持開放態度。我怎樣才能做到這一點?(漂亮管道和更少命名變數的加分!)
編輯 - 解決方案:
喬納森答案的修改版本給出了完全通用的解決方案。(另外,我還是更喜歡setdiff這里anti_join,雖然這只是個人喜好。)
test_df %>%
pivot_longer(cols = any_of(good_df$column), names_to = "column", values_to = "value") %>%
select(column, value) %>%
anti_join(good_df)
uj5u.com熱心網友回復:
這是 的代碼pivot_longer,缺失值可以通過以下方式獲得anti_join:
library(tidyverse)
test_df %>%
pivot_longer(c(col1, col2), names_to = "column", values_to = "value") %>%
anti_join(good_df)
uj5u.com熱心網友回復:
您可能還會考慮這種方法
cn = unique(good_df$column)
melt(test_df[,..cn], measure=cn,variable = "column")[!good_df, on=.(column, value)]
輸出:
column value
1: col2 D
wheretest_df和good_dfare 的類data.table。那是:
library(data.table)
setDT(good_df); setDT(test_df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488546.html
