簡體   English   中英

重復值的數據框

[英]Data frame of repeated values

我目前正在使用R。我有一個數據框,其中包含三個名稱,每列一個: year1year2year3 每列都有一組數字數據。

我想有一個產生的數據幀,其中包括了在兩個不同的列重復的數據,即:如果num.4在重復year1year2新的數據幀具有num.4 ,以同樣的方式,如果num.5重復在year2year3新的數據幀已num.5包括在內。

我嘗試了以下代碼:

newdf1 <- origdf[origdf$year1 == origdf$year2 | origdf$year1 == origdf$year3, c(1)]

newdf2 <- origdf[origdf$year2 == origdf$year3, c(2)]

然后合並兩個數據幀,但並未包括所有數據,它包含許多NA值。

然后,我嘗試了以下代碼:

newdf <- origdf[origdf$year1 == origdf$year2 | origdf$year1 == origdf$year3 & origdf$year2 == origdf$year3, c(1, 2)]

但這也沒有用,它給了我一個結果數據幀,其中包含許多NA值和一些正確的值,但並非所有重復的數字都包括在內。

如何有效地包含一個包含在原始數據幀的三個不同列中的恰好是重復的值的數據框,而沒有重復的值(我不想在第三個列的所有列中都包含一個重復的數字)原始數據幀)?

預期結果將是:

>newdf

1 num.4
2 num.5

如果我以正確的方式理解,您正在尋找數據框的各列之間的交集,但應排除 所有這三列共有的元素。 然后, intersect()函數可能是一個解決方案。 代碼看起來像這樣

n_years <- 3
# generate all possible combinations of two indices of considered years
indices_comb <- combn(x = 1:n_years, m = 2)
# apply intersect() along all possible combinations
all_intersects <- sapply(function(i) intersect(origdf[, indices_comb[1, i]], 
    origdf[, indices_comb[2, i]]), X = 1:ncol(indices_comb))

精細地,排除所有原始列( year1year2year3year2 year3

# find elements which are common for all pairwise intersections
in_all <- Reduce(intersect, all_intersects)
# combine all pairwise intersections into one vector
in_pairw <- Reduce(all_intersects, f = c)
# exclude the elements which are common for all intersections
newdf <- data.frame(res = setdiff(in_pairw, in_all))

上述解決方案可以輕松縮放為任意數量的原始列(年)。 但請注意,僅返回唯一的組合。 也就是說, num.4year1year2中都出現兩次,只返回一個num.4

暫無
暫無

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

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