![](/img/trans.png)
[英]Error of “In if (x == 1) { … : the condition has length > 1 and only the first element will be used”
[英]the condition has length > 1 and only the first element will be used error
if (crabs$FL >= median(crabs$FL)) {crabs$FLG <- "L"} else {crabs$FLG <- "S"}
螃蟹是數據名稱,FL 是變量名稱。 如果 FL 大於中位數,我正在嘗試創建一個變量名“FLG”。
但它說條件的長度> 1,並且只會使用第一個元素。 它創建了 FLG,但似乎只有第一行的值用於創建它。
if (crabs$FL[i] >= median(crabs$FL)) {crabs$FLG <- "L"} else {crabs$FLG <- "S"}
我試過這個。 但是現在它說 if (crabs$FL[i] >= median(crabs$FL)) {: missing value where TRUE/FALSE 需要錯誤。
請給我任何解決此錯誤的想法!
如果您不介意 tidyverse 方式,那么這段代碼應該可以讓您達到您想要的效果。
library(tidyverse)
crabs <- data.frame(FL = c(1,2,3,4,5,50000))
crabs_2 <- crabs %>%
mutate(
FLG = case_when(
FL >= median(FL) ~ 'L',
TRUE ~ 'S'
)
)
也許:
mutate(crabs, FLG = if_else(FL >= median(crabs$FL), 'L', 'S'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.