简体   繁体   中英

I want to create a loop with a large dataframe in R

Problem

I want to create a loop from data in df1 it's important the data is taken one ID value at a time.

I'm unsure how this can be done with R.

#original dataset
id=c(1,1,1,2,2,2,3,3,3)
dob=c("11-08","12-04","04-03","10-04","03-07","06-02","12-09","01-01","03-08")
count=c(1,6,3,2,5,6,8,6,4)
outcome=rep(1:0,length.out=9)
df1=data.frame(id,dob,count,outcome)

#changes for each value this needs to be completed separately for each value
df2<-df1[df1$id==1,]
df2<-df2[,-4]
addition<-df2$count+45
df2<-cbind(df2,addition)

df3<-df1[df1$id==2,]
df3<-df3[,-4]
addition<-df3$count+45
df3<-cbind(df3,addition)

df4<-df1[df1$id==3,]
df4<-df4[,-4]
addition<-df4$count+45
df4<-cbind(df4,addition)

df5<-rbind(df2,df3,df4)

Expected Output

df5<-rbind(df2,df3,df4)


1   1   11-08   1   46
2   1   12-04   6   51
3   1   04-03   3   48
4   2   10-04   2   47
5   2   03-07   5   50
6   2   06-02   6   51
7   3   12-09   8   53
8   3   01-01   6   51
9   3   03-08   4   49

In the present context (could be a simplified example) it doesn't even need that to loop, as we can directly add the 'count' with a number

df1$addition <- df1$count + 45

However, if it is a complicated operation and needs to look into the 'id' separately, then do a group_by operation

library(dplyr)
df1 %>% 
   group_by(id) %>% 
   mutate(addition = count + 45)
# A tibble: 9 x 5
# Groups:   id [3]
#     id dob   count outcome addition
#  <dbl> <fct> <dbl>   <int>    <dbl>
#1     1 11-08     1       1       46
#2     1 12-04     6       0       51
#3     1 04-03     3       1       48
#4     2 10-04     2       0       47
#5     2 03-07     5       1       50
#6     2 06-02     6       0       51
#7     3 12-09     8       1       53
#8     3 01-01     6       0       51
#9     3 03-08     4       1       49

Also, data.table syntax would be

library(data.table)
setDT(df1)[, addition := count + 45, by = id]

or simply

setDT(df1)[, addition := count + 45]

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