我创建了一个函数,它可以很好地处理虚拟数据。但是,当我在真实数据上运行这个函数时,我得到了一个错误
Error in wilcox.test.formula(tab[[dependent]] ~ as.factor(tab$group), :
grouping factor must have exactly 2 levels和警告信息:
In wilcox.test.default(x = c(11.2558701380866, 31.8401548036613, : cannot compute exact p-value with ties因此,在我的函数中,“阈值化”似乎不能正确地将真实数据分割成两组。另外,真实数据的子设置是不正确的。但我不明白为什么?虚拟表和实表结构似乎是一样的:
虚拟数据和真实数据的结构:
虚拟人:
> str(tab)
'data.frame': 80 obs. of 3 variables:
$ infGrad : num 14.15 12.53 3.03 9.21 16.36 ...
$ distance : int 1 1 1 1 1 1 1 1 1 1 ...
$ uniqueGroup: Factor w/ 2 levels "x","y": 1 2 1 2 1 2 1 2 1 2 ...Real:
> str(tab)
'data.frame': 142 obs. of 10 variables:
$ distance : num 100 100 100 100 100 100 100 100 100 100 ...
$ infGrad : num 11.3 17.4 31.8 11.1 47.8 ...
$ uniqueGroup: Factor w/ 6 levels "x",..: 5 2 5 2 5 5 5 5 3 6 ...我发现NAs可能会导致这些问题,或者wilcox.test(y ~ x)公式的规范。
因此,我尝试将na.omit添加到我的函数中,而不是wilcox.test(y~x),而是使用wilcox.test(y, x)。这些都不起作用。
您有什么想法吗,,如何使我的函数工作,或如何使使它更健壮的来接受我的真实数据?你的帮助是非常感谢的。
守则的作用是:
我使用嵌套的lapply运行函数,以改变阈值和不同的数据子集。
我的虚拟数据:
set.seed(10)
infGrad <- c(rnorm(20, mean=14, sd=8),
rnorm(20, mean=13, sd=5),
rnorm(20, mean=8, sd=2),
rnorm(20, mean=7, sd=1))
distance <- rep(c(1:4), each = 20)
uniqueGroup <- rep(c("x", "y"), 40)
tab<-data.frame(infGrad, distance, uniqueGroup)
# Create moving threshols function
movThreshold <- function(th, tab, dependent, ...) {
tab<-na.omit(tab)
# Classify data
tab$group<- ifelse(tab$distance < th, "a", "b") # does not WORK on REAL data
# Calculate wincoxon test
test<-wilcox.test(tab[[dependent]] ~ as.factor(tab$group), # specify column name
data = tab)
# Put results in a vector
c(th, dependent, round(test$p.value, 3))
}
# Define two vectors to run through
# unique group
gr.list<-unique(tab$uniqueGroup)
# unique threshold
th.list<-c(2,3,4)
# apply function over threshols and subset
res<-lapply(gr.list, function(x) lapply(th.list,
movThreshold,
tab = tab[uniqueGroup == x,], # does not work on REAL data
dependent = "infGrad"))在实际数据上似乎行不通的是:
lapply循环中的数据子集设置
制表符= tabuniqueGroup == x,发布于 2018-05-08 19:04:39
这个问题可能是因为一个单一的值组而发生的。您可以再现错误,例如,向th.list添加一个高值。
# unique threshold
th.list<-c(2,3,4,100)避免这种情况的最简单方法是在执行测试之前检查tab$group的长度。这一职能的改变应足以:
movThreshold <- function(th, tab, dependent, ...) {
tab<-na.omit(tab)
# Classify data
tab$group<- ifelse(tab$distance < th, "a", "b") # does not WORK on REAL data
# Check there are two groups
if(length(unique(tab$group))<2){return(NA)}
# Calculate wincoxon test
test<-wilcox.test(tab[[dependent]] ~ as.factor(tab$group), # specify column name
data = tab)
# Put results in a vector
c(th, dependent, round(test$p.value, 3))
}https://stackoverflow.com/questions/50239607
复制相似问题