簡體   English   中英

R - 基於列名(在向量中)和這些列中的特定值的子集行

[英]R - subset rows based on column names (in a vector) and specific values in those columns

這就是我的df的樣子:

df <- data.frame(WoS = c(1L, NA, 1L, NA, 1L, NA), Scopus = c(1L, 1L, 1L, 1L, NA, NA), Dim = c(NA, NA, 1L, 1L, 1L, 1L), Lens = c(NA, NA, NA, 1L, NA, 1L))

或者:

| WoS| Scopus| Dim| Lens| # (+ various other columns)
|---:|------:|---:|----:|
|   1|      1|  NA|   NA|
|  NA|      1|  NA|   NA|
|   1|      1|   1|   NA|
|  NA|      1|   1|    1|
|   1|     NA|   1|   NA|
|  NA|     NA|   1|    1|

# (+ hundreds of other rows in which 1 and NAs are distributed among these four columns)

我想根據存儲列名的向量對df進行子集化; 這些列中至少一列的值應等於1

vec提及的其他列應為NA

例子:

假設我有一個向量vec <- c("WoS", "Scopus")

然后我想 select df$WoS = 1 OR df$Scopus = 1的所有行,其中is.na(df$Dim)is.na(df$Lens)

| WoS| Scopus| Dim| Lens| # (+ keep all other columns ...)
|---:|------:|---:|----:|
|   1|      1|  NA|   NA|
|  NA|      1|  NA|   NA|
|   1|     NA|  NA|   NA|
|  NA|      1|  NA|   NA|
|   1|      1|  NA|   NA|

如何以最好的方式做到這一點?

我們可以將列名存儲到向量中,然后針對不同的條件應用filter

library(dplyr)

target1 <- c("WoS", "Scopus")
target2 <- c("Dim", "Lens")

df2 <- df %>%
  filter(rowSums(select(., all_of(target1)), na.rm = TRUE) <= 2) %>%
  filter(across(all_of(target2), .fns = is.na))
df2
#   WoS Scopus Dim Lens
# 1   1      1  NA   NA
# 2  NA      1  NA   NA

如果您不喜歡使用rowSums ,因為某些列中的值可能不是嚴格意義上的一,我們可以使用filterif_any更改為以下內容。

df2 <- df %>%
  filter(if_any(all_of(target1), .fns = function(x) x == 1)) %>%
  filter(across(all_of(target2), .fns = is.na))
df2
#   WoS Scopus Dim Lens
# 1   1      1  NA   NA
# 2  NA      1  NA   NA

我們還可以將第二個filter across中的 cross 更改為if_all

df2 <- df %>%
  filter(if_any(all_of(target1), .fns = function(x) x == 1)) %>%
  filter(if_all(all_of(target2), .fns = is.na))
df2
#   WoS Scopus Dim Lens
# 1   1      1  NA   NA
# 2  NA      1  NA   NA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM