gpt4 book ai didi

r - 是否可以根据变量标签选择列?

转载 作者:行者123 更新时间:2023-12-02 18:44:16 25 4
gpt4 key购买 nike

对于非常广泛的数据集,是否可以使用变量标签来选择列?

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"))

这不起作用,因为它会查找列名称。它可以查看标签吗?

编辑:除了将标签转换为列名称的明显作用之外,我还应该添加。

最佳答案

我们可以获得属性“标签”,检查“里程”

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(使用R 4.1.0),使用lapply循环遍历列,提取标签 属性,使用 grep 返回与 pattern 'Miles' 匹配的元素,获取 names 并在 中使用它选择子集

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
# ...

关于r - 是否可以根据变量标签选择列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67664582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com