這可能是一個簡單的答案,但我在尋找此解決方案時遇到問題,請尋求幫助。
> fruit.names <- c(rep("apple",3), rep("pear",3), rep("pepper", 3), rep("rice",3))
> adj <- c(rep("red", 3), rep("not round", 2), "yellow", rep("hot", 3), "grain", "white", "starch")
> df.start <- data.frame(fruit.names, adj)
> df.start
fruit.names adj
1 apple red
2 apple red
3 apple red
4 pear not round
5 pear not round
6 pear yellow
7 pepper hot
8 pepper hot
9 pepper hot
10 rice grain
11 rice white
12 rice starch
我需要的代碼只列出唯一的 df.start$names,并且在 df.start$adj 中對于 df.start$names 中的每個專案都有相同的結果。
所以結果看起來像這樣。如果可能的話,我寧愿只使用基礎 R(即沒有 tidyr/dplyr。)
> df.results
fruit.names adj
1 apple red
2 pepper hot
uj5u.com熱心網友回復:
幾種方式:
基數R
ind <- ave(df.start$adj, df.start$fruit.names, FUN = function(z) length(unique(z)) == 1) == "TRUE"
unique(df.start[ind,])
# fruit.names adj
# 1 apple red
# 7 pepper hot
需要對字串 進行檢查"TRUE"是因為ave要求其回傳值與輸入向量是同一類,因此輸出是強制的。
dplyr
(為人群提供,雖然我知道你說你更喜歡基數 R。)
library(dplyr)
df.start %>%
group_by(fruit.names) %>%
filter(length(unique(adj)) == 1) %>%
ungroup() %>%
distinct()
# # A tibble: 2 x 2
# fruit.names adj
# <chr> <chr>
# 1 apple red
# 2 pepper hot
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353843.html
上一篇:僅將可用日期值添加到每月資料框
