簡體   English   中英

如何在 R Data.frame 中使用 if/then 改變列

[英]How to mutate a column with if/then in R Data.frame

讓我們假設如果數據是

data <- head(iris)

我如何創建一個新列,其值將從data$Sepal.Length派生,如果data$Sepal.Length equal to or greater than 5value will be 5 ,如果less or equal to 3 ,則值為將是3 ,否則值應該保持不變......我試過

data %>% mutate(Sepal.Length = case_when(Sepal.Length <=3 ~ '3',Sepal.Length>=5 ~ '5'))

但它給了NA剩余價值..

您可以使用基本的case_when語句來執行此操作:

data %>% 
  mutate(Sepal.Length = case_when(
    Sepal.Length <= 3 ~ 3,
    Sepal.Length >= 5 ~ 5,
    TRUE ~ Sepal.Length))

#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1            5         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5            5         3.6          1.4         0.2  setosa
# 6            5         3.9          1.7         0.4  setosa```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM