问题
column a column b
10 2
30 3
40 4
in r, how can i divide column B's value by previous row value of column A
like 3/10 and 4/30
回答1:
Using Base R:
transform(dat,new=c(NA,head(column_a,-1))/column_b)
column_a column_b new
1 10 2 NA
2 30 3 3.333333
3 40 4 7.500000
回答2:
You can use lead() and lag()from dplyr, which finds the next or previous value in a vector:
library(dplyr)
df <- data.frame(a = c(10, 30, 40),
b = c(2, 3, 4))
First option: lead()
lead(df$b) / df$a
returns
[1] 0.3000000 0.1333333 NA
Second option: lag()
df$b / lag(df$a)
returns
[1] NA 0.3000000 0.1333333
回答3:
like this,
dta <- data.frame(column_a = c(10, 30, 40), column_b = c(2, 3, 4))
# install.packages(c("tidyverse""), dependencies = TRUE)
library(tidyverse)
tbl <- dta %>% as_tibble()
mutate(tbl, column_a_lag = lag(column_a), a_lag_div_b = column_a_lag/column_b)
#> # A tibble: 3 x 4
#> column_a column_b column_a_lag a_lag_div_b
#> <dbl> <dbl> <dbl> <dbl>
#> 1 10 2 NA NA
#> 2 30 3 10 3.333333
#> 3 40 4 30 7.500000
obliviously, you can also go there directly by,
tbl %>% mutate(lag_a = lag(column_a)/column_b, lead_b = column_a/lead(column_b))
#> # A tibble: 3 x 4
#> column_a column_b lag_a lead_b
#> <dbl> <dbl> <dbl> <dbl>
#> 1 10 2 NA 3.333333
#> 2 30 3 3.333333 7.500000
#> 3 40 4 7.500000 NA
I want to echo Sotos' comment above. It's generally good to demonstrate you already put some effort into it. In addition, you should always strive to rovide a complete minimal reproducible example to go along with your question. Something we can work from and use to show you how it might be possible to answer your question. I will also recommend to take a look at this post; how do I ask a good question, but since you are new to the site we try to help you getting started.
回答4:
Using data.table
dt[ , new:= column_b / shift(column_a)]
column_a column_b new
1: 10 2 NA
2: 30 3 0.3000000
3: 40 4 0.1333333
来源:https://stackoverflow.com/questions/48637745/divide-one-column-by-another-columns-previous-value