Search code examples
rpastestartswith

Using startsWith and paste0 together


I have a dataframe similar to the following:

Frequency  Period No.  Period
Q1         3
Q2         6
Q3         9 

If the value in the Frequency column starts with "Q", I want the Period column to be filled with the respective Quarter (i.e. if Frequency is Q1, the Period is Q1). I DO NOT want this to be done by simply pasting the values in the Frequency column to the Period column.

I'm currently trying to use startsWith and paste0 to do this:

df$Frequency[startsWith(df$Frequency, "Q")] <- paste0("Q", (df$`Period No.`)-1)%/%3+1)

I'm getting the error

Error in startsWith(df$Frequency, "Q") : 
  non-character object(s)

Can someone help with this issue?


Solution

  • We could use case_when or ifelse or simple assignment with index

    i1 <- grepl("^Q\\d+", df$Frequency)
    df$Period[i1] <- df$`Period No.`[i1]