【发布时间】:2019-09-03 11:01:28
【问题描述】:
我在 R 中有一个 data.frame(让我们以内置数据集“mtcars”为例),我想找到一种更有效的方法来创建第二个 data.frame,其中包含每个变量的描述(即一些基本元数据)以下列方式:
Variables Type Labels
mpg numeric Miles/(US) gallon
cyl numeric Number of cylinders
disp numeric Displacement (cu.in.)
hp numeric Gross horsepower
drat numeric Rear axle ratio
wt numeric Weight (1000 lbs)
qsec numeric 1/4 mile time
vs numeric Engine (0 = V-shaped, 1 = straight)
am numeric Transmission (0 = automatic, 1 = manual)
gear numeric Number of forward gears
carb numeric Number of carburetors
下面的代码表示我当前获取data.frame的方法,其中包含每个变量的描述,包括变量名称、变量元素类型和标签。
dat01 <- mtcars
Variables <- c(names(dat01))
#install.packages("Hmisc")
library(Hmisc)
var.labels = c(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 (0 = V-shaped, 1 = straight)",
am="Transmission (0 = automatic, 1 = manual)",
gear="Number of forward gears",
carb="Number of carburetors")
label(dat01) <- as.list(var.labels[match(names(dat01), names(var.labels))])
Labels <- label(dat01)
Type <- c(mode(dat01$mpg),
mode(dat01$cyl),
mode(dat01$disp),
mode(dat01$hp),
mode(dat01$drat),
mode(dat01$wt),
mode(dat01$qsec),
mode(dat01$vs),
mode(dat01$am),
mode(dat01$gear),
mode(dat01$carb))
meta.df <- data.frame(Variables,
Type,
Labels)
print(meta.df, row.names = FALSE)
除了提高我的脚本的效率(具体来说,我相信有更高效的代码可以用来创建向量“Type”),我也很想听听你关于如何最好地泛化的建议此脚本,以便它可以复制/粘贴并应用于类似结构的 data.frames。
【问题讨论】:
-
Type = sapply(mtcars, mode)会很标准。使其可泛化的方法是将其放入函数中,可能是数据的函数,将自定义标签作为可选参数。 -
我还想知道您是否确定
mode是您想要的信息。class更有用,但是您必须决定如何处理多类对象。但是mode(factor(1:3))、mode(Sys.Date())、mode(Sys.time())之类的都是numeric,这让我不喜欢模式。 -
当您说模式是数字时,我不确定您的意思。当我使用 mode(variable.name) 时,它返回一个字符串,指示数据元素的类型(即“字符”、“数字”、“逻辑”等)。似乎 class(variable.name) 做了同样的事情,除了 sapply(dat01, class) 还返回一行,表明我的数据框中的每一列都被“标记”了。
-
是的,
mode和class返回字符串。mode(Sys.Date())返回字符串"numeric",因为日期在内部存储为数字。class(Sys.Date())返回字符串"Date"。我的观点是class返回的信息更有用,因为因子、日期、时间戳和整数都将由mode标识为简单的"numeric",但class将区分它们和常规数字。class返回的信息通常更有帮助。 -
test_list = list(date = Sys.Date(), time = Sys.time(), factor = factor('a'), integer = 1L, numeric = 1.5)。比较lapply(test_list, mode)和lapply(test_list, class)。但是在这里你也可以看到class不一定返回长度为 1 的字符串,class(Sys.time())、class(factor('a', ordered = T))是具有多个类的两个基本示例......这会使事情变得更难。选择class(x)[1]将是一个非常好的默认值。
标签: r dataframe vector metadata mode