I have no problem showing the levels
of data dataframe using attributes(data$sex)$levels
.
But, how to do it with pipe
? I tried data %>% attributes(sex)$levels
but it gives an error.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
set.seed(22)
data <- data.frame(age = floor(rnorm(6,25,10)),
sex = gl(2,1,6, labels = c("f","m")))
var.labels <- c(age = "Age in Years",
sex = "Sex of the participant")
tibble::as_tibble(data)
#> # A tibble: 6 × 2
#> age sex
#> <dbl> <fct>
#> 1 19 f
#> 2 49 m
#> 3 35 f
#> 4 27 m
#> 5 22 f
#> 6 43 m
attributes(data$sex)$levels
#> [1] "f" "m"
# How to do it using pipe?
data %>% attributes(sex)$levels
#> Error in `$`(., attributes(sex), levels): 3 arguments passed to '$' which requires 2
Created on 2022-08-19 by the reprex package (v2.0.1)
CodePudding user response:
Wrap with {}
and use .$
to extract the column
library(dplyr)
data %>%
{attributes(.$sex)$levels}
[1] "f" "m"
Or use the standard dplyr methods
data %>%
pull(sex) %>%
levels
[1] "f" "m"
Or use exposition operator (%$%
) from magrittr
library(magrittr)
data %$%
attributes(sex)$levels
[1] "f" "m"
CodePudding user response:
- We can use
Base R
pip
data |> with(attributes(sex)$levels)
[1] "f" "m"