簡體   English   中英

如果所有值都匹配 R 中的條件,則選擇行

[英]Selecting rows if all values match criteria in R

我在R有一個名為records的數據框。 這是該數據幀的摘錄:

head(records[430:438,12:16])

     2B2_pyr_hor 2B3_pyr_hor 3A1_pyr_hor 3A2_pyr_hor 3A3_pyr_hor
3760    22.45732    21.63635    24.36742    20.11058    28.10608
3761    33.81917    31.96332    36.45907    29.76239    41.94274
3762    47.38274    44.32909    51.10520    41.49609    57.54125
3763    62.47752    58.20380    67.02381    54.71055    74.55541
3764    78.17504    73.55406    83.88879    69.30802    92.57984
3905    90.84730    94.72380    89.43837   106.69484    81.44858

我想提取所有行,所有的值都<100 ,但是當我做records=records[records<100,]看來我得到的所有的行,其中至少一個值小於<100

所以在這個例子中,我不想要index=3905行,但我仍然得到它。 (以上摘錄是在我應用后records=records[records<100,]

不幸的是,我過去的第一次搜索沒有產生任何有用的解決方案。 一定是我在某個地方遺漏了一些簡單的東西?

我們可以使用rowSums

df[rowSums(df < 100) == ncol(df), ]
#Alternative version : 
#df[rowSums(df >= 100) == 0, ]

#     2B2_pyr_hor 2B3_pyr_hor 3A1_pyr_hor 3A2_pyr_hor 3A3_pyr_hor
#3760        22.5        21.6        24.4        20.1        28.1
#3761        33.8        32.0        36.5        29.8        41.9
#3762        47.4        44.3        51.1        41.5        57.5
#3763        62.5        58.2        67.0        54.7        74.6
#3764        78.2        73.6        83.9        69.3        92.6

或者使用lapplyReduce

df[Reduce(`&`, lapply(df, `<`, 100)), ]

數據

df <- structure(list(`2B2_pyr_hor` = c(22.45732, 33.81917, 47.38274, 
62.47752, 78.17504, 90.8473), `2B3_pyr_hor` = c(21.63635, 31.96332, 
44.32909, 58.2038, 73.55406, 94.7238), `3A1_pyr_hor` = c(24.36742, 
36.45907, 51.1052, 67.02381, 83.88879, 89.43837), `3A2_pyr_hor` = c(20.11058, 
29.76239, 41.49609, 54.71055, 69.30802, 106.69484), `3A3_pyr_hor` = c(28.10608, 
41.94274, 57.54125, 74.55541, 92.57984, 81.44858)), class = "data.frame", 
row.names = c("3760","3761", "3762", "3763", "3764", "3905"))

您可以使用applyall來選擇所有值都低於 100 的行

records[apply(records<100, 1, all),]
#     X2B2_pyr_hor X2B3_pyr_hor X3A1_pyr_hor X3A2_pyr_hor X3A3_pyr_hor
#3760     22.45732     21.63635     24.36742     20.11058     28.10608
#3761     33.81917     31.96332     36.45907     29.76239     41.94274
#3762     47.38274     44.32909     51.10520     41.49609     57.54125
#3763     62.47752     58.20380     67.02381     54.71055     74.55541
#3764     78.17504     73.55406     83.88879     69.30802     92.57984

暫無
暫無

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

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