Home > Net >  find same rows with for loop
find same rows with for loop

Time:11-29

id<-c(1,1,2,2,3,3,3,4,4,4,4,4,5,5,5)
sample<-c(2010,2010,2011,2012,2013,2012,2013,2013,2014,2015,2014,2015,2015,2015,2015)

df<-cbind(id,sample)

Let him check the numbers in the id column here. If it is the same, assign 1, if it is different, assign a variable such as 2.

I want to do it but I can't. do this with a for loop if possible. find different row ids that are the same. assign another variable

for(i in seq(df)){
  df[i,3]<-ifelse(df[i,1]==df[i 1,1],1,df[i,3] 1)
}

CodePudding user response:

If I understood correctly, this might help you

id <- c(1,1,2,2,3,3,3,4,4,4,4,4,5,5,5)
sample <- c(2010,2010,2011,2012,2013,2012,2013,2013,2014,2015,2014,2015,2015,2015,2015)

library(dplyr)

tibble(id,sample) %>% 
  mutate(check = if_else(id == lead(id),1,2))

# A tibble: 15 x 3
      id sample check
   <dbl>  <dbl> <dbl>
 1     1   2010     1
 2     1   2010     2
 3     2   2011     1
 4     2   2012     2
 5     3   2013     1
 6     3   2012     1
 7     3   2013     2
 8     4   2013     1
 9     4   2014     1
10     4   2015     1
11     4   2014     1
12     4   2015     2
13     5   2015     1
14     5   2015     1
15     5   2015    NA
  • Related