我有一个数据框,其中包含来自蝾螈内脏的各种节肢动物的长度和宽度。因为有些内脏有数千种特定的猎物,我只测量了每种猎物类型的一个子集。我现在想用该猎物的平均长度和宽度替换每个未测量的个体。我想保留数据框并只添加估算列(length2,width2)。主要原因是每一行都有关于收集蝾螈的日期和位置的数据列。我可以用随机选择的测量个体来填充 NA,但为了论证,我们假设我只想用平均值替换每个 NA。
例如,假设我有一个看起来像这样的数据框:
id taxa length width
101 collembola 2.1 0.9
102 mite 0.9 0.7
103 mite 1.1 0.8
104 collembola NA NA
105 collembola 1.5 0.5
106 mite NA NA
实际上,我有更多的列和大约 25 个不同的分类群,总共有大约 30,000 个猎物。看起来 plyr 包可能是理想的,但我只是不知道如何做到这一点。我不是很懂 R 或编程,但我正在努力学习。
并不是说我知道自己在做什么,但如果有帮助,我会尝试创建一个小数据集来玩。
exampleDF <- data.frame(id = seq(1:100), taxa = c(rep("collembola", 50), rep("mite", 25),
rep("ant", 25)), length = c(rnorm(40, 1, 0.5), rep("NA", 10), rnorm(20, 0.8, 0.1), rep("NA",
5), rnorm(20, 2.5, 0.5), rep("NA", 5)), width = c(rnorm(40, 0.5, 0.25), rep("NA", 10),
rnorm(20, 0.3, 0.01), rep("NA", 5), rnorm(20, 1, 0.1), rep("NA", 5)))
以下是我尝试过的一些事情(没有奏效):
# mean imputation to recode NA in length and width with means
(could do random imputation but unnecessary here)
mean.imp <- function(x) {
missing <- is.na(x)
n.missing <-sum(missing)
x.obs <-a[!missing]
imputed <- x
imputed[missing] <- mean(x.obs)
return (imputed)
}
mean.imp(exampleDF[exampleDF$taxa == "collembola", "length"])
n.taxa <- length(unique(exampleDF$taxa))
for(i in 1:n.taxa) {
mean.imp(exampleDF[exampleDF$taxa == unique(exampleDF$taxa[i]), "length"])
} # no way to get back into dataframe in proper places, try plyr?
另一种尝试:
imp.mean <- function(x) {
a <- mean(x, na.rm = TRUE)
return (ifelse (is.na(x) == TRUE , a, x))
} # tried but not sure how to use this in ddply
Diet2 <- ddply(exampleDF, .(taxa), transform, length2 = function(x) {
a <- mean(exampleDF$length, na.rm = TRUE)
return (ifelse (is.na(exampleDF$length) == TRUE , a, exampleDF$length))
})
有什么建议么?