簡體   English   中英

R.根據一秒內的值保留一個數據幀中的行

[英]R. Retaining rows from one data frame based on values in a second

我有兩個數據幀。 一個數據框由四列組成,第四列包含一個指向物理位置的數字。

第二個數據框也有四列。 第2列和第3列是指邊界。

當V4中指定的數字落在數據幀2的任何行中指定的V2和V3之間時,我試圖保留數據幀1中的每一行。 因此,如果來自數據幀1的V4的62765落在20140803-20223538,63549983-63556677或52236330-52315441之間的示例中的數據幀2中,則應該保留整行,否則它將被省略。

我還希望能夠執行相反的操作,即當V4不在數據幀2中的V2和V3之間時保留每一行。 這里的任何幫助將不勝感激。

數據框一

V1 V2         V3  V4
10 rs11511647  0  62765
10 rs12218882  0  84172
10 rs10904045  0  84426
10 rs11252127  0  88087  

數據框兩

V1  V2         V3     V4
 7 20140803 20223538   7A5
19 63549983 63556677  A1BG
10 52236330 52315441  A1CF 

這是一個簡單的appraoch:

# check whether values of df1$V4 are between df2$V2 and df2$V3
idx <- sapply(df1$V4, function(x) any(x >= df2$V2 & x <= df2$V3))

# remove rows
df1[idx, ]

# retain rows
df1[!idx, ]

修訂

使用@ akrun的數據並從@Sven Hohenstein的代碼中獲取靈感,這是另一種方法。

df1 <- data.frame(
       V1 = c(10,10,10,10),
       V2 = c("rs11511647","rs12218882","rs10904045", "rs11252127"),
       V3 = c(0,0,0,0),
       V4 = c(62765, 63549985, 84426, 88087),
       stringsAsFactors=FALSE)

df2 <- data.frame(
       V1 = c(7, 19, 10),
       V2 = c(20140803, 63549983, 52236330),
       V3 = c(20223538, 63556677, 52315441),
       V4 = c("7A5", "A1BG", "A1CF"),
       stringsAsFactors=FALSE)

library(dplyr)

df1 %>%
    rowwise %>%
    mutate(test = ifelse(any(V4 >= df2$V2 & V4 <= df2$V3), 1, 0)) %>%
    filter(test == 1)

#  V1         V2 V3       V4 test
#1 10 rs12218882  0 63549985    1

這是另一種可能性

idx <- sapply(seq(nrow(df1)), function(y) {
    df1$V4[y] > df2[y,2] & df1$V4[y] < df2[y,3]
})
df1[match(TRUE, idx),]
#   V1         V2 V3       V4
# 2 10 rs12218882  0 63549985

暫無
暫無

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

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