Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

replace - Replacing 0 values with the minimum value of the row in r

I have data like this original data

I want to replace 0 values with the minimum value of each row (excluding 0), and I tried the following code

gapFill_data <- 
  data %>% 
  mutate_all(., ~ replace(., . == 0, min(as.numeric(.[.>0]))))

It doesn't work, and give me warnings like "In min(as.numeric(.[. > 0])) : no non-missing arguments to min; returning Inf." Below is the transformed data. transformed data

I have tried to replace "min(as.numeric(.[.>0])))" with "5" in the code, then all 0 values were replaces with 5. So I guess the problem is here "min(as.numeric(.[.>0])))". Any suggestion is appreciated.

question from:https://stackoverflow.com/questions/65950557/replacing-0-values-with-the-minimum-value-of-the-row-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

mutate is used to operate on data column-wise. If you want to do this rowwise one way in base R would be to use apply with margin as 1.

gapFill_data <- data

gapFill_data[] <- t(apply(data, 1, function(x) 
                          replace(x, x == 0, min(x[x > 0], na.rm = TRUE))))

gapFill_data

#  a b c d
#1 1 3 1 1
#2 2 2 3 2
#3 3 4 2 2
#4 4 2 1 1
#5 5 3 4 3

data

data <- data.frame(a = 1:5, b = c(3, 0, 4, 2, 3), c = c(0, 3, 2, 1, 4), d = 0)
data
#  a b c d
#1 1 3 0 0
#2 2 0 3 0
#3 3 4 2 0
#4 4 2 1 0
#5 5 3 4 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...