r - 如何在 R 中仅显示带标签的数据框中的一种类型的属性

标签 r

我只想显示一种类型的属性(例如标签),此代码显示所有三种类型。

library(tidyverse)
library(labelled)

df <- tibble(age = c(10,20,30),
             sex = c(1,1,2))

df$sex <- labelled(
  c(1, 1, 2),
  c(Male = 1, Female = 2),
  label = "Assigned sex at birth"
)

# how to show only one attribute e.g. labels?
showAt <- function(db, v) {
  at <- df %>% 
    pull({{v}}) %>% 
    attributes
  return(at)
}

showAt(df, sex)
#> $labels
#>   Male Female 
#>      1      2 
#> 
#> $label
#> [1] "Assigned sex at birth"
#> 
#> $class
#> [1] "haven_labelled" "vctrs_vctr"     "double"
Created on 2022-08-19 by the reprex package (v2.0.1)

最佳答案

我们可以使用pluck

library(purrr)
library(dplyr)
showAt <- function(db, v) {
  at <- db %>% 
    pull({{v}}) %>% 
    attributes %>%
    pluck("labels")
  return(at)
}

-测试

> showAt(df, sex)
  Male Female 
     1      2 

关于r - 如何在 R 中仅显示带标签的数据框中的一种类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73419947/

相关文章:

r - 如何循环 lapply 以在 R 中的多个变量上创建 LAG 项

r - 如何从 R Matrix 库访问稀疏矩阵的一些元素?

R dplyr : group by without aggregate function

r - 多维矩阵查找,如何改进缓慢的解决方案

r - 从 R 中的 lm 中提取变量以使用预测

r - ggplot2版本0.9.3.1不会加载到R 3.0.2中

r - dplyr 在匿名函数中执行多个绘图

r - R 中的跟踪函数

使用具有条件的另一个数据帧替换一个数据帧中多列的值

r - 在 ggplot2 中跨几何均匀应用抖动