简体   繁体   English

根据R中另一列的值对一列进行赋值

[英]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: 我有一个data.frame ,其列的值介于3到18之间。我想要做的是创建一个新的列,其值从4到14。

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 然后,当lace$TOTAL.LACE > 4 && lace$TOTAL.LACE < 13] <- lace$TOTAL.LACE lace$TOTAL.LACE时,我想使lace$New.Lace等于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. 最终只使lace$New.Lace等于lace$TOTAL.LACE因此向量变得相同。

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, 谢谢,

In this case you can just iterate over TOTAL.Lace values and assign values to New.Lace based on your condition. 在这种情况下,您可以仅遍历TOTAL.Lace值,然后根据您的条件将值分配给New.Lace。 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 . 但是似乎应该<- 14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM