Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205399

r for loop with if else statement and reference to outcome of previous iteration

$
0
0

I am having a dataframe with field x containing both group names (labeled as letters in the example below) and members of the group (listed under the group names, labeled as a number). I want to create a field that shows for each member the name of its group. In the dataframe below the desired output is shown in column "outcome".

df <- data.frame("x"=c("A","1","2","B","C","1","2","C","D","1"),
                 "outcome"=c("A","A","A","B","C","C","C","C","D","D")
) %>%
  mutate(
    Letter = ifelse(grepl("[A-Za-z]", x) == T,"Letter",
                      "No Letter")
  )

My idea is to do this via a forloop. If x is a letter it should return that letter, if not it should return the outcome of the previous loop (which is the previous found letter in x). The forloop below doesn't give the right output:

df$outcome_calc[1] <- "A" 
for (i in 2:10) {  
  df$outcome_calc[i] <- ifelse(df$Letter[i] == "No Letter",df$outcome_calc[i-1],df$x[i])    

}

Any ideas how to get the right output?


Viewing all articles
Browse latest Browse all 205399

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>