Home > front end >  How to do operations only on specific cells of dataframe in R dplyr
How to do operations only on specific cells of dataframe in R dplyr

Time:05-18

I have data frame below and I want to keep everything unchanged except for the last cell.
I want it to be rounded to the nearest top integer. Is there any way to target one or more specific cells using dplyr?

    df <- data.frame(id = c(rep(101, 4), rep(202, 2), "tot"),
                status = c("a","b","c","d", "a", "b", "cccc"),
                wt = c(100,200,100,105, 20,22,10000),
                ht = c(5.3,5.2,5,5.1, 4.3,4.2,4.9))


> df
   id status    wt  ht
1 101      a   100 5.3
2 101      b   200 5.2
3 101      c   100 5.0
4 101      d   105 5.1
5 202      a    20 4.3
6 202      b    22 4.2
7 tot   cccc 10000 4.9

my desired out put is :

df[df$id=="tot", 4] <- round(df[df$id=="tot", 4])
> df
   id status    wt  ht
1 101      a   100 5.3
2 101      b   200 5.2
3 101      c   100 5.0
4 101      d   105 5.1
5 202      a    20 4.3
6 202      b    22 4.2
7 tot   cccc 10000 5.0

CodePudding user response:

A possible solution, based on dplyr:

library(dplyr)

df %>% 
  mutate(ht = if_else(row_number() == n(), round(ht,0), ht))

#>    id status    wt  ht
#> 1 101      a   100 5.3
#> 2 101      b   200 5.2
#> 3 101      c   100 5.0
#> 4 101      d   105 5.1
#> 5 202      a    20 4.3
#> 6 202      b    22 4.2
#> 7 tot   cccc 10000 5.0
  • Related