Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65923016/r-looping-through-rows-per-factor-with-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...