简体   繁体   中英

R: Looping through rows per factor with a function

I need to calculate a New value based on Value2 and the newly created previous value of the same New column.

But additionally I want to do this per Group. I made a for loop previously but it stopped working when i added a second loop for the groups.

for(j in 1:(*EACHGROUP*){
    for(i in 2:nrow(DAT) #Start at second place in each Group
      DAT$New[i] <- ( DAT$New[i-1]*10^(DAT$Value2[i]) )}

Dummy data

Year <- c(1980,1990,2000,2005,1993,2008,1999,2003,2005)
Group <- c("A","A","A","A","B","B","C","C","C")
Value2 <- c(0,0.25,0.1,-0.3,.5,0.7,-0.8,0.01,0.2)
New <- c(1,1,1,1,1,1,1,1,1)
DAT <- data.frame(cbind(Year,Group,Value2,New))

Output:  
  Year Group Value2 New
1 1980     A      0   1
2 1990     A   0.25   1
3 2000     A    0.1   1
4 2005     A   -0.3   1
5 1993     B    0.5   1
6 2008     B    0.7   1
7 1999     C   -0.8   1
8 2003     C   0.01   1
9 2005     C    0.2   1

How can I continue with this approach?

Or should I use "dplyr" for example to do this more easily?

Desired result

  Year Group Value2  New
1 1980     A      0    1
2 1990     A   0.25 1.78
3 2000     A    0.1 2.24
4 2005     A   -0.3 1.12
5 1993     B    0.5    1
6 2008     B    0.7 5.01
7 1999     C   -0.8    1
8 2003     C   0.01 1.02
9 2005     C    0.2 1.62

Best regards

Here is a dplyr way, with an auxiliary function fun .

fun <- function(x, y){
  for(i in seq_along(x)[-1]){
    x[i] <- x[i - 1] * 10^y[i]
  }
  x
}

DAT %>%
  group_by(Group) %>%
  mutate(New = fun(New, Value2))
## A tibble: 9 x 4
## Groups:   Group [3]
#   Year Group Value2   New
#  <dbl> <chr>  <dbl> <dbl>
#1  1980 A       0     1   
#2  1990 A       0.25  1.78
#3  2000 A       0.1   2.24
#4  2005 A      -0.3   1.12
#5  1993 B       0.5   1   
#6  2008 B       0.7   5.01
#7  1999 C      -0.8   1   
#8  2003 C       0.01  1.02
#9  2005 C       0.2   1.62

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM