我在 R 中有一個資料框,其中有許多重復的行:
| 標題1 | 標頭2 |
|---|---|
| 金槍魚 | 蘋果 |
| 橙 | 三文魚 |
| 橙 | 鱒魚 |
| 藍色的 | 鱒魚 |
| 橙 | 三文魚 |
| 金槍魚 | 蘋果 |
如您所見,第 1 行和第 6 行以及第 2 行和第 5 行彼此完全相同。
我想洗掉重復項,但創建第三列,其中列出出現次數:
| 標題1 | 標頭2 | 新:出現次數 |
|---|---|---|
| 金槍魚 | 蘋果 | 2 |
| 橙 | 三文魚 | 2 |
| 橙 | 鱒魚 | 1 |
| 藍色的 | 鱒魚 | 1 |
有誰知道我該怎么做?我真的被困住了。任何幫助深表感謝。
---------
[我確實拍了很多張照片。我不認為他們接近正確,但這是我正在嘗試的]:
countx = 1
county = 2
while (county <= 6){
if ((df[countx,] == df[county,]) == T & T){
print("true")
} else {
print ("false")
}
county <- county 1
}
但是,即使只有一列與另一列匹配,這也會回傳“true”——例如,第 2 行中的“橙色”和第 3 行中的“橙色”,即使該行中的另一個單元格不匹配。
我也在嘗試 if else ,但真的不知道該去哪里:
if(duplicated(df[1,])==T){
xx
}else{
xx
}
如您所知,我是一個自學成才的新手,我試圖在我的論文中使用 R 并且有點不知所措。非常感謝任何幫助!蒂亞!
uj5u.com熱心網友回復:
最簡單的方法是簡單地使用countfrom dplyr:
library(dplyr)
df %>%
count(header1, header2)
輸出
header1 header2 n
1 blue trout 1
2 orange salmon 2
3 orange trout 1
4 tuna apple 2
或與tally:
df %>%
group_by(header1, header2) %>%
tally() %>%
ungroup
或其他選項data.table:
library(data.table)
dt <- as.data.table(df)
dt[, list(count =.N), by=list(header1, header2)]
或者您可以使用ddplyfrom plyr:
plyr::ddply(df, c("header1", "header2"), nrow)
更新
如果 2 列的順序無關緊要,那么您可以這樣做,我們首先將每一行拆分為串列中自己的資料框。然后,我們可以sort將 2 列折疊成每一行的一個字串,然后我們可以使用 計數出現次數table,然后轉換回資料框。
split(df2, seq(nrow(df2))) %>%
sapply(., function(x)
unlist(x) %>% sort() %>% paste(collapse = " ")) %>%
table(combo = .) %>%
data.frame
或者我們也可以tidyverse通過使用purrr:
library(tidyverse)
df2 %>%
pmap_dfr(~list(...)[order(c(...))] %>% set_names(names(df2))) %>%
group_by_all %>%
count
輸出
combo Freq
1 apple tuna 3
2 blue trout 1
3 orange salmon 2
4 orange trout 1
資料
df2<- structure(list(header1 = c("tuna", "orange", "orange", "blue",
"orange", "tuna", "apple"), header2 = c("apple", "salmon", "trout",
"trout", "salmon", "apple", "tuna")), class = "data.frame", row.names = c(NA,
-7L))
# header1 header2
#1 tuna apple
#2 orange salmon
#3 orange trout
#4 blue trout
#5 orange salmon
#6 tuna apple
#7 apple tuna
uj5u.com熱心網友回復:
一個可能的解決方案:
library(dplyr)
df %>%
group_by(header1, header2) %>%
summarise(n = n(), .groups = "drop")
#> # A tibble: 4 × 3
#> header1 header2 n
#> <chr> <chr> <int>
#> 1 blue trout 1
#> 2 orange salmon 2
#> 3 orange trout 1
#> 4 tuna apple 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/487578.html
上一篇:根據每個名稱的觀察次數過濾資料
