微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为 unique() 函数使用管道

如何解决为 unique() 函数使用管道

下面是我用来对数据集 tan1 的列状态组进行模式插补的代码。 如何使用管道重写相同的内容unique() 函数似乎在管道中不起作用。

NA_stat <- unique(tan1$status_group[!is.na(tan1$status_group)])

mode <- NA_stat[which.max(tabulate(match(tan1$status_group,NA_stat)))]

tan1$status_group[is.na(tan1$status_group)] <- mode  

另外,我如何对多个列应用相同的过程?

解决方法

以下是确定和输入管道模式的一些示例。

计算模式的函数:

library(tidyverse)

# Single mode (returns only the first mode if there's more than one)
# https://stackoverflow.com/a/8189441/496488
# Modified to remove NA
Mode <- function(x) {
  ux <- na.omit(unique(x))
  ux[which.max(tabulate(match(x,ux)))]
}

# Return all modes if there's more than one
# https://stackoverflow.com/a/8189441/496488
# Modified to remove NA
Modes <- function(x) {
  ux <- na.omit(unique(x))
  tab <- tabulate(match(x,ux))
  ux[tab == max(tab)]
}

将函数应用于数据框:

iris %>% 
  summarise(across(everything(),Mode))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1            5           3          1.4         0.2  setosa

iris %>% map(Modes)
#> $Sepal.Length
#> [1] 5
#> 
#> $Sepal.Width
#> [1] 3
#> 
#> $Petal.Length
#> [1] 1.4 1.5
#> 
#> $Petal.Width
#> [1] 0.2
#> 
#> $Species
#> [1] setosa     versicolor virginica 
#> Levels: setosa versicolor virginica

使用该模式估算缺失数据。但请注意,我们使用 Mode,它在有多种模式的情况下仅返回第一种模式。如果您有多种模式,您可能需要调整您的方法。

# Create missing data
d = iris
d[1,] = rep(NA,ncol(iris))

head(d)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1           NA          NA           NA          NA    <NA>
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

# Replace missing values with the mode
d = d %>% 
  mutate(across(everything(),~coalesce(.,Mode(.))))

head(d)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 1          5.0         3.0          1.5         0.2 versicolor
#> 2          4.9         3.0          1.4         0.2     setosa
#> 3          4.7         3.2          1.3         0.2     setosa
#> 4          4.6         3.1          1.5         0.2     setosa
#> 5          5.0         3.6          1.4         0.2     setosa
#> 6          5.4         3.9          1.7         0.4     setosa

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。