如何列出每个类别的所有唯一值

时间:2019-02-07 16:39:57

标签: r

我有两列,第一列是商务功能(上游,下游,中游等),另一列是这些功能所在的城市。还有许多其他功能和城市,但我在这里将其缩小了看起来像这样:

Function      City
DownStream   Edmonton
Downstream   Edmonton
upstream     Edmonton
Upstream     Calgary
Midstream    Calgary
Midstream    Calgary
Midtream     Edmonton
Upstream     Vancouver

我知道unique()函数将返回我要查找的unqiue值,但是我无法创建将“功能”列分组的内容,然后为每个功能列出唯一的城市。

最终结果如下:

Functions  City

Downstream Edmonton


Midstream  Edmonton 
           Calgary 


Upstream   Edmonton
           Calgary
           Vancouver

这里有一些示例数据可供使用

# Create sample data
Function=c("DownStream", "DownStream", "Upstream", "Upstream", "Midstream", 
           "Midstream", "Midstream", "Upstream")
City=c("Edmonton", "Edmonton", "Edmonton", "Calgary","Calgary", "Calgary",
       "Edmonton", "Vancouver")
df <- data.frame(Function, City)

2 个答案:

答案 0 :(得分:1)

我建议先获取唯一的行,然后再将其替换为NA。

# Create sample data
Function=c("DownStream", "DownStream", "Upstream", "Upstream", "Midstream", 
           "Midstream", "Midstream", "Upstream")
City=c("Edmonton", "Edmonton", "Edmonton", "Calgary", "Calgary", "Calgary", 
       "Edmonton", "Vancouver")
df <- data.frame(Function, City)

# Get unique rows and replace duplicates with NA
unique_df <- unique(df)
unique_df[duplicated(unique_df[,"Function"]),"Function"] <- NA
print(unique_df)

答案 1 :(得分:0)

首先在R中创建一个数据帧,例如df=data.frame(Function, City),然后简单地unique(Function, City)就会给出结果。
或使用dplyr软件包,然后运行以下代码 df %>% group_by(Function) %>% distinct(City)