Home > Blockchain >  Fill value of a numeric with the entry of another row based on name
Fill value of a numeric with the entry of another row based on name

Time:05-26

Good day, I have a dataframe that looks like this;

  Community Value   Num
  <chr>     <dbl> <dbl>
1 A          3.54     3
2 A          4.56     3
3 A          2.22     3
4 B          0       NA
5 B          0.76    NA
6 C          1.2      5

I am hoping to fill the Num observation of Community B with the Num observation of Community A while keeping the names as is.

CodePudding user response:

If this is all you need to do, you can try using an if_else() statement. If your greater problem is more complex, you might need to take another approach.

library(dplyr)

df %>% 
  mutate(Num = if_else(Community == "B", Num[Community == "A"][1], Num))

#   Community Value Num
# 1         A  3.54   3
# 2         A  4.56   3
# 3         A  2.22   3
# 4         B  0.00   3
# 5         B  0.76   3
# 6         C  1.20   5

Data:

df <- read.table(textConnection("Community Value   Num
A          3.54     3
A          4.56     3
A          2.22     3
B          0       NA
B          0.76    NA
C          1.2      5"), header = TRUE)

CodePudding user response:

If the NA values will always be immediately below the positive values with which you want to replace them, you can use fill:

library(tidyr)
df %>%
  fill(Num, .direction = "down") 
  • Related