gpt4 book ai didi

r - 如何用列中最小值的一半替换零?

转载 作者:行者123 更新时间:2023-12-04 02:39:44 25 4
gpt4 key购买 nike

我试图用该列中大于零的最小值的一半替换我的数千行和列的数据框中的 0。我也不想包括前四列,因为它们是索引。

所以如果我从这样的事情开始:

index <- c("100p", "200p", 300p" 400p")
ratio <- c(5, 4, 3, 2)
gene <- c("gapdh", NA, NA,"actb"
species <- c("mouse", NA, NA, "rat")
a1 <- c(0,3,5,2)
b1 <- c(0, 0, 4, 6)
c1 <- c(1, 2, 3, 4)

as.data.frame(q) <- cbind(index, ratio, gene, species, a1, b1, c1)

index ratio gene species a1 b1 c1
100p 5 gapdh mouse 0 0 1
200p 4 NA NA 3 0 2
300p 3 NA NA 5 4 3
400p 2 actb rat 2 6 4

我希望获得这样的结果:

index ratio gene  species a1 b1 c1
100p 5 gapdh mouse 1 2 1
200p 4 NA NA 3 2 2
300p 3 NA NA 5 4 3
400p 2 actb rat 2 6 4

我试过下面的代码: apply(q[-4], 2, function(x) "[<-"(x, x==0, min(x[x > 0]) / 2))

但我一直收到错误:Error in min(x[x > 0])/2 : non-numeric argument to binary operator

有什么帮助吗?非常感谢!

最佳答案

我们可以使用lapply并将列中具有最小值的0值替换为2。

cols<- 5:7
q[cols] <- lapply(q[cols], function(x) replace(x, x == 0, min(x[x>0], na.rm = TRUE)/2))

q
# index ratio gene species a1 b1 c1
#1 100p 5 gapdh mouse 1 2 1
#2 200p 4 <NA> <NA> 3 2 2
#3 300p 3 <NA> <NA> 5 4 3
#4 400p 2 actb rat 2 6 4

dplyr中,我们可以使用mutate_at

library(dplyr)
q %>% mutate_at(cols,~replace(., . == 0, min(.[.>0], na.rm = TRUE)/2))

数据

q <- structure(list(index = structure(1:4, .Label = c("100p", "200p", 
"300p", "400p"), class = "factor"), ratio = c(5, 4, 3, 2), gene = structure(c(2L,
NA, NA, 1L), .Label = c("actb", "gapdh"), class = "factor"),
species = structure(c(1L, NA, NA, 2L), .Label = c("mouse",
"rat"), class = "factor"), a1 = c(0, 3, 5, 2), b1 = c(0,
0, 4, 6), c1 = c(1, 2, 3, 4)), class = "data.frame", row.names = c(NA, -4L))

关于r - 如何用列中最小值的一半替换零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59951719/

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