Reputation: 457
I have a data frame of several rows, and I would like to have each one of its rows divided by its index. For example, I have:
1 10 20 15 23
2 10 20 15 23
3 10 20 15 23
4 10 20 15 23
And I would like to get:
1 10 20 15 23
2 5 10 7.5 11.5
3 3.33 6.66 5 7.66
4 2.5 5 3.75 5.75
Upvotes: 1
Views: 283
Reputation: 388862
Multiple ways to do this, easiest would be
df / 1:nrow(df)
# V1 V2 V3 V4
#1 10.000000 20.000000 15.00 23.000000
#2 5.000000 10.000000 7.50 11.500000
#3 3.333333 6.666667 5.00 7.666667
#4 2.500000 5.000000 3.75 5.750000
A dplyr
option
library(dplyr)
df %>%
group_by(n = row_number()) %>%
mutate_all(funs(./n)) %>%
ungroup() %>%
select(-n)
# V1 V2 V3 V4
# <dbl> <dbl> <dbl> <dbl>
#1 10.0 20.0 15.0 23.0
#2 5.00 10.0 7.50 11.5
#3 3.33 6.67 5.00 7.67
#4 2.50 5.00 3.75 5.75
Upvotes: 6
Reputation: 4970
For completeness. You could try.
df/1:dim(df)[1]
V2 V3 V4 V5
1 10.000000 20.000000 15.00 23.000000
2 5.000000 10.000000 7.50 11.500000
3 3.333333 6.666667 5.00 7.666667
4 2.500000 5.000000 3.75 5.750000
Other option.
df/seq(length(df))
Based on comment below.
df/row(df)
Upvotes: 3
Reputation: 2707
With tidyverse
:
read_table(" 10 20 15 23
10 20 15 23
10 20 15 23
10 20 15 23",col_names=F)%>%
mutate_all(as.numeric)%>%
mutate_at(vars(X1:X4), .funs =funs( ./row_number()))
# A tibble: 4 x 4
X1 X2 X3 X4
<dbl> <dbl> <dbl> <dbl>
1 10.0 20.0 15.0 23.0
2 5.00 10.0 7.50 11.5
3 3.33 6.67 5.00 7.67
4 2.50 5.00 3.75 5.75
Upvotes: 1