gpt4 book ai didi

在 R 中读取缺失值的文件

转载 作者:行者123 更新时间:2023-12-01 12:47:05 24 4
gpt4 key购买 nike

我有一个 filename = 'fn' 的文件,我正在读取它,如下所示:

age CALCIUM CREATININE  GLUCOSE
64.3573 1.1 488
69.9043 8.1 1.1 472
65.6633 8.6 0.8 461
50.3693 8.1 1.3 418
57.0334 8.7 0.8 NEG
81.4939 1.1 NEG
56.954 9.8 1
76.9298 9.1 0.8 NEG


> tmpData = read.table(fn, header = TRUE, sep= "\t" , na.strings = c('', 'NA', '<NA>'), blank.lines.skip = TRUE)
> tmpData
age CALCIUM CREATININE GLUCOSE
1 64.3573 NA 1.1 488
2 69.9043 8.1 1.1 472
3 65.6633 8.6 0.8 461
4 50.3693 8.1 1.3 418
5 57.0334 8.7 0.8 NEG
6 81.4939 NA 1.1 NEG
7 56.9540 9.8 1.0 <NA>
8 76.9298 9.1 0.8 NEG

文件如上读取,缺失值替换为 NA 和 < NA >。我猜想“葡萄糖”列被视为因素。有没有一种简单的方法可以将 < NA > 解释为真正的 NA 并将任何非数字值转换为 NA(在此示例中 NEG 转换为 NA)

最佳答案

您可以利用 as.numeric 将非数字值强制转换为 NA 这一事实。换句话说,尝试这样的事情:

这是您的数据:

temp <- structure(list(age = c(64.3573, 69.9043, 65.6633, 50.3693, 57.0334, 
81.4939, 56.954, 76.9298), CALCIUM = c(1.1, 8.1, 8.6, 8.1, 8.7,
1.1, 9.8, 9.1), CREATININE = c(NA, 1.1, 0.8, 1.3, 0.8, NA, 1,
0.8), GLUCOSE = structure(c(5L, 4L, 3L, 2L, 6L, 6L, 1L, 6L), .Label = c("",
"418", "461", "472", "488", "NEG"), class = "factor")), .Names = c("age",
"CALCIUM", "CREATININE", "GLUCOSE"), class = "data.frame", row.names = c(NA,
-8L))

及其当前结构:

str(temp)
# 'data.frame': 8 obs. of 4 variables:
# $ age : num 64.4 69.9 65.7 50.4 57 ...
# $ CALCIUM : num 1.1 8.1 8.6 8.1 8.7 1.1 9.8 9.1
# $ CREATININE: num NA 1.1 0.8 1.3 0.8 NA 1 0.8
# $ GLUCOSE : Factor w/ 6 levels "","418","461",..: 5 4 3 2 6 6 1 6

将最后一列转换为数字,但由于它是一个因子,我们需要先将其转换为字符。注意警告。我们对此感到非常高兴。

temp$GLUCOSE <- as.numeric(as.character(temp$GLUCOSE))
# Warning message:
# NAs introduced by coercion

结果:

temp
# age CALCIUM CREATININE GLUCOSE
# 1 64.3573 1.1 NA 488
# 2 69.9043 8.1 1.1 472
# 3 65.6633 8.6 0.8 461
# 4 50.3693 8.1 1.3 418
# 5 57.0334 8.7 0.8 NA
# 6 81.4939 1.1 NA NA
# 7 56.9540 9.8 1.0 NA
# 8 76.9298 9.1 0.8 NA

为了好玩,这里有一个我放在一起的小函数,它提供了另一种方法:

makemeNA <- function (mydf, NAStrings, fixed = TRUE) {
if (!isTRUE(fixed)) {
mydf[] <- lapply(mydf, function(x) gsub(NAStrings, "", x))
NAStrings <- ""
}
mydf[] <- lapply(mydf, function(x) type.convert(
as.character(x), na.strings = NAStrings))
mydf
}

此函数可让您指定一个正则表达式 来确定什么应该是NA 值。我还没有真正对其进行太多测试,所以使用正则表达式功能需要您自担风险!

使用与上面相同的“temp”对象,尝试这些以查看函数的作用:

# Change anything that is just text to NA
makemeNA(temp, "[A-Za-z]", fixed = FALSE)
# Change any exact matches with "NEG" to NA
makemeNA(temp, "NEG")
# Change any matches with 3-digit integers to NA
makemeNA(temp, "^[0-9]{3}$", fixed = FALSE)

关于在 R 中读取缺失值的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14897904/

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