简体   繁体   English

如何从 R 中的 data.frame 中提取唯一元素?

[英]How to extract unique elements from a data.frame in R?

Can someone suggest a way to extract unique elements from a data.frame?有人可以建议一种从 data.frame 中提取唯一元素的方法吗?

I have noticed unique , but since it works on either rows or columns, it doesn't do what I'm looking for.我注意到unique ,但由于它适用于行或列,因此无法满足我的要求。 I'm after unique cells from a data.frame.我正在寻找来自 data.frame 的独特单元格。

eg,例如,

df<-data.frame(V1=c("Hello","fat","man"),V2=c("cat","fat","Hello"),V3=c("man","dog","black"))

Extracting unique elements should give me c("Hello","fat","man","cat","dog","black")提取独特的元素应该给我c("Hello","fat","man","cat","dog","black")

A 'data.frame' can be considered as a 'list' with columns as 'list' elements having the same length. “data.frame”可以被认为是一个“列表”,其中的列是具有相同长度的“列表”元素。 By using unlist , we can convert it to vector and then get the unique values and convert to 'character' class with as.character .通过使用unlist ,我们可以将其转换为vector ,然后获取unique值并使用as.character转换为 'character' 类。

as.character(unique(unlist(df)))

Or simply:或者干脆:

unique(as.vector(as.matrix(df)))
## [1] "Hello" "fat"   "man"   "cat"   "dog"   "black"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM