r-如何设置一行中每列的类型



当我使用自己的数据时,我喜欢用这种方式创建数据集:

颜色逻辑患者生病了吗
出生日期 身高 生病
日期 数字列表
出生日期 体重(cm(头发颜色
1991年3月20日 163 1 蓝色
1993年11月10日 185 0 棕色

这里有一个通用的方法;"类型";您可能需要。

第一个前提是,我们对您可能拥有的每种类型都有明确的功能,即

funcs <- list(
guess   = function(z) type.convert(z, as.is = TRUE),
skip    = identity,
logical = function(z) !is.na(z) & tolower(z) %in% c("1", "true"),
numeric = as.numeric,
date    = function(z) as.Date(z, format = "%d/%m/%Y"),
text    = as.character,
list    = as.list)

数据的基本清理以提取类型,

types <- unlist(data_work[1,])
labels <- unlist(data_work[2,])
data_work <- data_work[-(1:2),]
data_work
#     birthdate height   sick  color
#        <char> <char> <char> <char>
# 1: 20/03/1991    163      1   blue
# 2: 10/11/1993    185      0  brown

从这里开始,我们将Map每列及其各自的函数:

cols <- names(data_work)[ types %in% names(funcs) ]
funs <- funcs[ types[ types %in% names(funcs) ] ]
data_work[, (cols) := Map(function(f, x) f(x), funs, .SD), 
.SDcols = cols]
#     birthdate height   sick  color
#        <Date>  <num> <lgcl> <list>
# 1: 1991-03-20    163   TRUE   blue
# 2: 1993-11-10    185  FALSE  brown

数据

data_work <- structure(list(birthdate = c("date", "Date of birth", "20/03/1991", "10/11/1993"), height = c("numeric", "Weight (cm)", "163", "185"), sick = c("logical", "Is the patient sick ?", "1", "0"), color = c("list", "Hair color", "blue", "brown")), class = "data.frame", row.names = c(NA, -4L))
setDT(data_work)
data <- read.csv("data.csv", sep=",", header= TRUE)
data <- as.data.table(data)

data是问题中的数据表,包括标题后的第一行(带有数据类型(和列名时,下面会将第一行中的所有列(例如"date"(作为date_columns,然后相应地更改这些列的数据类型。

date_columns <- colnames(data)[grepl("date",data[1,])]
data[ ,(date_columns) := lapply(.SD, as.Date), .SDcols = date_columns]

只需对要检测的每种类型重复这两个步骤(将代码中的"日期"替换为其他数据类型(。之后,您可以从数据表中删除指定类型的第一行。

最新更新