[英]Extract rows from data in R with conditions on features
我在RStudio中加載了一個數據集,其中包含6個輸入要素和2個輸出,並包含4000個障礙。 我想根據此數據構建另一個數據集,其中包含5個輸入要素的固定值,並且只有一個輸入是變化的。 假設我的數據由下式給出:
In1 In2 In3 In4 In5 In6 Out1 Out2
4 3 2 4 2 10 0.4 0.5
4 3 2 3 2 7 0.6 0.8
2 3 1 4 2 9 0.2 0.1
4 3 2 4 2 8 0.8 0.7
4 5 6 4 2 1 0.9 0.1
4 3 2 4 2 3 0.4 0.5
我想獲得的是(其中除了In6之外所有輸入都是恆定的)
In1 In2 In3 In4 In5 In6 Out1 Out2
4 3 2 4 2 10 0.4 0.5
4 3 2 4 2 8 0.8 0.7
4 3 2 4 2 3 0.4 0.5
我如何在R中做到這一點? 非常感謝您的幫助。
這會從輸入中生成請求的輸出,但是我不知道它是否可以推廣到更廣泛的情況。
首先,我定義數據幀df
df <- read.table(text = "In1 In2 In3 In4 In5 In6 Out1 Out2
4 3 2 4 2 10 0.4 0.5
4 3 2 3 2 7 0.6 0.8
2 3 1 4 2 9 0.2 0.1
4 3 2 4 2 8 0.8 0.7
4 5 6 4 2 1 0.9 0.1
4 3 2 4 2 3 0.4 0.5", header = TRUE)
然后,我在第1至5列中查找重復的行。
df[duplicated(df[, 1:5])|duplicated(df[, 1:5], fromLast = TRUE),]
# In1 In2 In3 In4 In5 In6 Out1 Out2
# 1 4 3 2 4 2 10 0.4 0.5
# 4 4 3 2 4 2 8 0.8 0.7
# 6 4 3 2 4 2 3 0.4 0.5
這將嘗試所有可能的輸入組合。 我從6個輸入中找到了5列的所有可能組合。
col_combinations <- combn(1:6, 5)
然后,我測試每個。
apply(col_combinations, MAR = 2,
function(x)df[duplicated(df[, x])|duplicated(df[, x], fromLast = TRUE),])
如您所見,只有一個成功。
# [[1]]
# In1 In2 In3 In4 In5 In6 Out1 Out2
# 1 4 3 2 4 2 10 0.4 0.5
# 4 4 3 2 4 2 8 0.8 0.7
# 6 4 3 2 4 2 3 0.4 0.5
#
# [[2]]
# [1] In1 In2 In3 In4 In5 In6 Out1 Out2
# <0 rows> (or 0-length row.names)
#
# [[3]]
# [1] In1 In2 In3 In4 In5 In6 Out1 Out2
# <0 rows> (or 0-length row.names)
#
# [[4]]
# [1] In1 In2 In3 In4 In5 In6 Out1 Out2
# <0 rows> (or 0-length row.names)
#
# [[5]]
# [1] In1 In2 In3 In4 In5 In6 Out1 Out2
# <0 rows> (or 0-length row.names)
#
# [[6]]
# [1] In1 In2 In3 In4 In5 In6 Out1 Out2
# <0 rows> (or 0-length row.names)
df = read.table(text = "
In1 In2 In3 In4 In5 In6 Out1 Out2
4 3 2 4 2 10 0.4 0.5
4 3 2 3 2 7 0.6 0.8
2 3 1 4 2 9 0.2 0.1
4 3 2 4 2 8 0.8 0.7
4 5 6 4 2 1 0.9 0.1
4 3 2 4 2 3 0.4 0.5
", header=T)
library(dplyr)
df %>%
group_by(In1,In2,In3,In4,In5) %>% # for those variables
mutate(n = n()) %>% # count number of combination and add it as a column
ungroup() %>% # forget the grouping
filter(n == max(n)) %>% # return the rows with the most popular combination
select(-n) # remove the counts
# # A tibble: 3 x 8
# In1 In2 In3 In4 In5 In6 Out1 Out2
# <int> <int> <int> <int> <int> <int> <dbl> <dbl>
# 1 4 3 2 4 2 10 0.4 0.5
# 2 4 3 2 4 2 8 0.8 0.7
# 3 4 3 2 4 2 3 0.4 0.5
這種方法假定您將始終擁有一個獲勝者組合,並且只在乎該獲勝者組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.