[英]Value a column based on the value of another column in R
我有一個data.frame
,其列的值介於3到18之間。我想要做的是創建一個新的列,其值從4到14。
lace$New.Lace[lace$TOTAL.LACE == 3] <- 4
lace$New.Lace[lace$TOTAL.LACE >= 14] <- 13
然后,當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
我嘗試執行以下操作:
lace$New.Lace[lace$TOTAL.LACE > 4 && lace$TOTAL.LACE < 13] <- lace$TOTAL.LACE
最終只使lace$New.Lace
等於lace$TOTAL.LACE
因此向量變得相同。
我應該怎么寫呢? 我已經將指令寫為:
lace$New.Lace[lace$TOTAL.LACE == 4] <- 4
lace$New.Lace[lace$TOTAL.LACE == 5] <- 5
...
這是一個痛苦的屁股。
謝謝,
在這種情況下,您可以僅遍歷TOTAL.Lace值,然后根據您的條件將值分配給New.Lace。 像這個例子:
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
}
}
我使用了您的原始條件:
lace$New.Lace[lace$TOTAL.LACE >= 14] <- 13
但是似乎應該<- 14
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.