是否可以根据变量标签选择列? [英] Is it possible to select columns based on variable labels?
本文介绍了是否可以根据变量标签选择列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于非常宽的数据集,是否可以使用变量标签来选择列?
library(expss)
data(mtcars)
mtcars = apply_labels(mtcars,
mpg = "Miles/(US) gallon",
cyl = "Number of cylinders",
disp = "Displacement (cu.in.)",
hp = "Gross horsepower",
drat = "Rear axle ratio",
wt = "Weight (1000 lbs)",
qsec = "1/4 mile time",
vs = "Engine",
vs = c("V-engine" = 0,
"Straight engine" = 1),
am = "Transmission",
am = c("Automatic" = 0,
"Manual"=1),
gear = "Number of forward gears",
carb = "Number of carburetors"
)
mtcars %>%
select(contains("Miles"))
这不起作用,因为它查看列名。它可以改为查看标签吗?
编辑:除了将标签转换为列名这一明显的操作外,我还应该添加。
推荐答案
我们可以获得attributes
‘Label’,检查‘Miles’
library(dplyr)
library(stringr)
mtcars %>%
select(where(~ str_detect(attributes(.)$label, 'Miles')))
-输出
# mpg
#Mazda RX4 21.0
#Mazda RX4 Wag 21.0
#Datsun 710 22.8
#Hornet 4 Drive 21.4
#Hornet Sportabout 18.7
#Valiant 18.1
#Duster 360 14.3
#Merc 240D 24.4
#Merc 230 22.8
#Merc 280 19.2
#Merc 280C 17.8
#Merc 450SE 16.4
# ..
或使用base R
(withR 4.1.0
),使用lapply
循环列,提取labels
属性,使用grep
返回与pattern
‘Miles’匹配的元素,获取names
并在subset
select
中使用
mtcars |>
lapply((x) attributes(x)$label) |>
grep(pattern = 'Miles', value = TRUE) |>
names() |>
{(x) subset(mtcars, select = x)}()
-输出
# mpg
#Mazda RX4 21.0
#Mazda RX4 Wag 21.0
#Datsun 710 22.8
#Hornet 4 Drive 21.4
#Hornet Sportabout 18.7
#Valiant 18.1
#Duster 360 14.3
#Merc 240D 24.4
#Merc 230 22.8
#Merc 280 19.2
# ...
这篇关于是否可以根据变量标签选择列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文