hrkshr
hrkshr

Reputation: 129

Loop variable names in R

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)]

Upvotes: 0

Views: 57

Answers (1)

Jan
Jan

Reputation: 5254

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)]
}

Upvotes: 1

Related Questions