在数据框中的所有列中找到唯一值的计数,而不包括NA值(R)
给定可重现的数据框,我想在每列中找到不包括缺失(NA)值的唯一值数。下面的代码计数Na值,因此,nat_country
列的基数显示为n_unique_values
dataframe中的4(应该为3)。在Python中,存在nunique()
函数,该功能不考虑Na值。在R中,如何实现这一目标?
nat_country = c("United-States", "Germany", "United-States", "United-States", "United-States", "United-States", "Taiwan", NA)
age = c(14,15,45,78,96,58,25,36)
dat = data.frame(nat_country, age)
n_unique_values = t(data.frame(apply(dat, 2, function(x) length(unique(x)))))
Given a reproducible dataframe, I want to find the number of unique values in each column not including missing (NA) values. Below code counts NA values, as a result the cardinality of nat_country
column shows as 4 in n_unique_values
dataframe (it is supposed to be 3). In python there exists nunique()
function which does not take NA values into consideration. In r how can one achieve this?
nat_country = c("United-States", "Germany", "United-States", "United-States", "United-States", "United-States", "Taiwan", NA)
age = c(14,15,45,78,96,58,25,36)
dat = data.frame(nat_country, age)
n_unique_values = t(data.frame(apply(dat, 2, function(x) length(unique(x)))))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
dplyr :: n_distinct
na.rm = t
:在基本r中,您可以使用
na.omit
:You can use
dplyr::n_distinct
withna.rm = T
:In base R, you can use
na.omit
as well:我们可以使用
MAP
或map_dfr
n_distinct
:We could use
map
ormap_dfr
withn_distinct
:在基础r 中,您可以使用
表
。如果要更改默认行为,它还具有参数USENA
。In base R you can use
table
. It also has a parameteruseNA
if you want to change the default behavior.