I have the following issue:
I have two dfs, called
df1anddf2.With the given
ifelsefunction I try to find all rows in thedf2$Indexwhich starts with the same three characters as indf1$Index_1.Search all cells starting with
CEE.Then take all the growth values and thedf2$Indexvalues that are atCEEand one before (Period 1). etc. The df: Result1 shows what the final result (just for the first row) looks like.The function should run through the entire vector Index_1 & Period. At the end there should be 5 dfs with the result.
The
ifelsefunction should identify the start point, and if the point was founded, then it should use the number in the period list to give the Growth anddf2$Indexvalues back, as already mentioned above. I tried it with theifelsefunction but I am sure there is a better and easier way to do this, moreover, theiflesefunction is not complete due to my lack of knowledge in R. It would be very nice if someone can help me.
Period <- c(1,2,3,4,5)
Index_1 <- c("CEE","DAE","ABC","EBB","BDC")
Growth <- c(10:34)
Index <- c("ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB" )  
Df1 <- data.frame(Period, Index_1)
Df2 <- data.frame(Growth,Index)
ss <- as.data.frame(ifelse(substr(Df2$Index, 1,3) == df1$Index_1,1,0))
Result1 <- data.frame(Index, Growth)
Index <- c("BDCE","CEED","BDCE","CEED","BDCE","CEED","BDCE","CEED","BDCE","CEED")
Growth <- c(11,12,16,17,21,22,26,27,31,32)
Result2 <- data.frame(Index, Growth)
Index <- c("BDCE", "CEED", "DAEB","BDCE", "CEED", "DAEB","BDCE", "CEED", "DAEB","BDCE", "CEED", "DAEB","BDCE", "CEED", "DAEB")
Growth <- c(11,12,13,16,17,18,21,22,13,26,27,28,31,32,33)
Second Question
Period <- c(3,2,1,4,5)
Index_1 <- c("CEE","DAE","ABC","EBB","BDC")
Growth <- c(10:34)
Index <- c("ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB","ABCD","BDCE", "CEED", "DAEB", "EBBB" )  
Df1 <- data.frame(Period, Index_1)
Df2 <- data.frame(Growth,Index)
lst <- apply(Df1, 1, function(x) {
  match_rows <- which(substr(Df2$Index, 1, 3) == x[["Index_1"]])
  all_rows <- unlist(Map(`:`, match_rows - as.numeric(x[["Period"]]), match_rows))
  Df2[all_rows[all_rows > 0],]
})
lst[[1]] # This is how it looks now
#and this is how it should look like
Result3 <- data.frame(Index, Growth) 
Index <- c("NA","ABCD","BDCE", "CEED","EBBB","ABCD","BDCE", "CEED","EBBB","ABCD","BDCE", "CEED","EBBB","ABCD","BDCE", "CEED","EBBB","ABCD","BDCE", "CEED")
Growth <- c(NA,10,11,12,14,15,16,17,19,20,21,22,24,25,26,27)