0

I have a complicated data structure and I would like to create a monthly dataset. The following code is how to construct columns. It is an ugly form. What kind of strategy can be used to simplify the code?

df2$emp_01 = df$month1_emplvl[which(df$qtr == 1)]
df2$emp_02 = df$month2_emplvl[which(df$qtr == 1)]
df2$emp_03 = df$month3_emplvl[which(df$qtr == 1)]
df2$emp_04 = df$month1_emplvl[which(df$qtr == 2)]
df2$emp_05 = df$month2_emplvl[which(df$qtr == 2)]
df2$emp_06 = df$month3_emplvl[which(df$qtr == 2)]
df2$emp_07 = df$month1_emplvl[which(df$qtr == 3)]
df2$emp_08 = df$month2_emplvl[which(df$qtr == 3)]
df2$emp_09 = df$month3_emplvl[which(df$qtr == 3)]
df2$emp_10 = df$month1_emplvl[which(df$qtr == 4)]
df2$emp_11 = df$month2_emplvl[which(df$qtr == 4)]
df2$emp_12 = df$month3_emplvl[which(df$qtr == 4)]
2
  • 2
    Do you really need a loop. It seems like a group by operation Commented May 26, 2020 at 21:10
  • 4
    I suggest you show us a little of your data. Edit your post to show the results of dput(head(df2)) . That will show us your columns. I assume that you have a collection df1, df2, df3...? Do they all have the same columns? Commented May 26, 2020 at 21:16

1 Answer 1

1

You can do this surprisingly easy once you realise that you can subset data with ["string"]. This first sample shows how it works:

for (i in 1:12) {
  month <- paste0("month", ((i-1) %% 3)+1, "_emplvl")
  thisqtr <- ( (i-1) %/% 3)+1
  cat(month, "  ", thisqtr, "\n")
}

Now, the solution is still theoretical. Without a sample of your data I have to "theorise". But it should show you how it works and even in case it still does not, it is close enough so that you can find your onw one with this.

for (i in 1:12) {
  month <- paste0("month", ((i-1) %% 3)+1, "_emplvl")
  thisqtr <- ( (i-1) %/% 3)+1
  df2[[paste0("emp_", i)]] <- df[[month]][which(df$qtr == thisqtr)]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.