【问题标题】:using pipes for unique() function为 unique() 函数使用管道
【发布时间】:2021-02-05 18:22:22
【问题描述】:

下面是我用来对数据集 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  

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

【问题讨论】:

  • 如果不知道您的数据就很难知道,也许dplyr::distinct() 可能有用,但是如果您与我们分享会很棒dput(tan1)

标签: r pipe unique multiple-columns


【解决方案1】:

以下是确定和估算管道中模式的一些示例。

计算模式的函数:

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

【讨论】:

    猜你喜欢
    • 2011-11-14
    • 2018-01-08
    • 2021-02-02
    • 1970-01-01
    • 2012-03-14
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多