For example, how can I divide by 2 only the rows ranging from 25 to 45 on a dataset that has 100 rows?
Asked
Active
Viewed 847 times
-3
-
1Please provide a complete example. – G. Grothendieck Jul 13 '20 at 02:25
-
It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 13 '20 at 03:35
2 Answers
2
BOD is a builtin 6x2 data frame whose columns are both numeric. These solutions require dplyr 1.0.0 or later.
1) This checks whether the row number is between 3 and 5 inclusive and if so divides by 2 and otherwise does not. If some of the columns are not numeric then replace everything()
with where(is.numeric)
so that the division only applies to the numeric columns.
library(dplyr)
BOD %>% mutate(across(everything(), ~ if_else(row_number() %in% 3:5, ./2, .)))
2) This alternative uses magrittr's %<>% operator but it does overwrite BOD in the sense that it will leave a modified version of BOD whereas the above preserves it and returns the result.
library(dplyr)
library(magrittr)
BOD[3:5, ] %<>% mutate(across(everything(), ~ ./2))

G. Grothendieck
- 254,981
- 17
- 203
- 341
1
You can subset the rows which are in range, divide and replace.
rows <- 25:45
df[rows, ] <- df[rows, ]/2
With a reproducible example dividing row numbers 3 to 4.
set.seed(456)
df <- data.frame(a = sample(100, 5), b = sample(100, 5))
df
# a b
#1 35 78
#2 38 31
#3 85 73
#4 27 79
#5 25 90
rows <- 3:4
df[rows, ] <- df[rows, ]/2
df
# a b
#1 35.0 78.0
#2 38.0 31.0
#3 42.5 36.5
#4 13.5 39.5
#5 25.0 90.0

Ronak Shah
- 377,200
- 20
- 156
- 213