Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何用新值替换矩阵中数据的百分比_R - Fatal编程技术网

R 如何用新值替换矩阵中数据的百分比

R 如何用新值替换矩阵中数据的百分比,r,R,我需要将矩阵中5%的值替换为数字0.2(在我的代码中是猜测),如果它们低于0.2,请不要管它们,如果它们高于0.2 现在,我的代码正在将所有小于0.2的值更改为0.2 这将在一个更大的循环中最终发生在多个复制中,但现在我正试图让它只工作1次 说明: gen.probs.2PLM是一个包含概率的矩阵。猜测是我选择用来取代其他人的价值。Perc是我希望在矩阵中查看的百分比,如果它小于猜测值,则会进行更改 gen.probs.2PLM <- icc.2pl(gen.theta,a,b,N,TL)

我需要将矩阵中5%的值替换为数字0.2(在我的代码中是猜测),如果它们低于0.2,请不要管它们,如果它们高于0.2

现在,我的代码正在将所有小于0.2的值更改为0.2

这将在一个更大的循环中最终发生在多个复制中,但现在我正试图让它只工作1次

说明: gen.probs.2PLM是一个包含概率的矩阵。猜测是我选择用来取代其他人的价值。Perc是我希望在矩阵中查看的百分比,如果它小于猜测值,则会进行更改

gen.probs.2PLM <- icc.2pl(gen.theta,a,b,N,TL)

perc<-0.05*N

guess<-0.2

gen.probs.2PLM[gen.probs.2PLM < guess] <- guess

以下是一个函数,您可以应用于数值矩阵,将低于某个阈值的5%的值(例如,在您的情况下为
.2
)替换为阈值:

replace_5pct <- function(d, threshold=.2){
  # get indices of cells below threshold, sample 5% of them 
  cells_below <- which(d < threshold)
  cells_to_modify <- sample(cells_below, size=.05*length(cells_below))
  # then replace values for sampled indices with threshold + return 
  d[cells_to_modify] <- threshold
  return(d)
}
您可以查看数据以确认结果,也可以查看如下统计数据:

mean(dat < .2)                # somewhere between .1 and .2 probably 
sum(dat != dat_5pct_replaced) # about 5% of mean(dat < .2)
平均值(dat<.2)#可能介于.1和.2之间
总和(dat!=dat#5pt#u替换)#约为平均值的5%(dat<.2)
p.s.:如果你想对函数进行泛化,你也可以对5%的替换进行抽象——然后你可以替换低于某个阈值的10%的值,等等。如果你想变得有趣,你也可以对“小于”进行抽象,并在主函数中添加一个比较函数作为参数

replace_func <- function(d, func, threshold, prop){
    cells <- which(func(d, threshold))
    cells_to_modify <- sample(cells, size=prop*length(cells))
    d[cells_to_modify] <- threshold
    return(d)
}

replace\u func请提供
gen.probs.2PLM
的示例。欢迎使用stackoverflow!通过遵循本指南,您可以为回答此问题提供坚实的基础。特别是,最有必要提供一个(最少、完整且可验证的示例)。查看有关R特定MCVE的提示。很好看,谢谢你的贡献!我在问题中添加了gen.probs.2PLM的图像。。。这是一个大矩阵。
5%
什么?在所有矩阵项或下面的矩阵项中
0.
?抱歉,这可能不是我想要的。如果我理解正确的话,它将占0.2以下所有单元格的5%,并对其进行更改。。我需要它来获取所有数据的5%,并且只改变那些低于0.2的数据。是的,这就是我理解要陈述的问题的方式。另请看更新答案的底部,它以一种可能有用的方式概括了解决方案。
mean(dat < .2)                # somewhere between .1 and .2 probably 
sum(dat != dat_5pct_replaced) # about 5% of mean(dat < .2)
replace_func <- function(d, func, threshold, prop){
    cells <- which(func(d, threshold))
    cells_to_modify <- sample(cells, size=prop*length(cells))
    d[cells_to_modify] <- threshold
    return(d)
}
# (need to backtick infix functions like <, >, etc.) 
replace_func(dat, func=`>`, threshold=.5, prop=.1)