MCP_infiltrator
MCP_infiltrator

Reputation: 4179

Value a column based on the value of another column in R

I have a data.frame with a column that has values from 3 to 18. What I am trying to do is make a new column that is valued from 4 to 14. I want to roll my data up in the following way:

lace$New.Lace[lace$TOTAL.LACE == 3] <- 4
lace$New.Lace[lace$TOTAL.LACE >= 14] <- 13

I want to then make lace$New.Lace equal to lace$TOTAL.LACE when lace$TOTAL.LACE > 4 && lace$TOTAL.LACE < 13] <- lace$TOTAL.LACE

I tried doing the following:

lace$New.Lace[lace$TOTAL.LACE > 4 && lace$TOTAL.LACE < 13] <- lace$TOTAL.LACE

This ends up just making lace$New.Lace equal to lace$TOTAL.LACE so the vectors become identical.

How should I be writing this? I have already just written the instructions as:

lace$New.Lace[lace$TOTAL.LACE == 4] <- 4
lace$New.Lace[lace$TOTAL.LACE == 5] <- 5
...

Which is a pain in the butt.

Thank you,

Upvotes: 1

Views: 41

Answers (1)

Ardavel
Ardavel

Reputation: 1515

In this case you can just iterate over TOTAL.Lace values and assign values to New.Lace based on your condition. Like in this example:

tl = 18:3
df = data.frame(tl)
df$nl = df$tl
for (i in 1:length(df$tl)) {
  if (df$tl[i] <= 4) {
    df$nl[i] = 4
  } else if (df$tl[i] >= 14) {
    df$nl[i] = 13
  }
}

I used your original condition:

lace$New.Lace[lace$TOTAL.LACE >= 14] <- 13

however it seems that it should be <- 14.

Upvotes: 1

Related Questions