![](/img/trans.png)
[英]How to use mutate for a new column based the data in multiple existing columns
[英]Derive or Mutate a new column based on conditions on existing columns
我有一個數據框,如下所示。 我想根據某些條件在現有列的基礎上派生一個新列。
我想最好使用dplyr
包來實現。
例如:只要結果值大於1,則將結果導出為1,否則得出0。
datetime outcome
12/1/2017 1
12/2/2017 1
12/3/2017 1
12/4/2017 2
12/5/2017 1
12/6/2017 1
12/7/2017 1
具有派生變量的預期數據幀:
datetime outcome result
12/1/2017 1 0
12/2/2017 1 0
12/3/2017 1 0
12/4/2017 2 1
12/5/2017 1 0
12/6/2017 1 0
12/7/2017 1 0
一種方法如下。 我稱您的數據為foo
。 您想要使用邏輯檢查來檢查每個值是否大於1。 as.numeric()
將TRUE轉換為1,將FALSE轉換為0。
library(dplyr)
foo %>%
mutate(check = as.numeric(outcome > 1))
datetime outcome check
1 12/1/2017 1 0
2 12/2/2017 1 0
3 12/3/2017 1 0
4 12/4/2017 2 1
5 12/5/2017 1 0
6 12/6/2017 1 0
7 12/7/2017 1 0
數據
foo <- structure(list(datetime = structure(1:7, .Label = c("12/1/2017",
"12/2/2017", "12/3/2017", "12/4/2017", "12/5/2017", "12/6/2017",
"12/7/2017"), class = "factor"), outcome = c(1L, 1L, 1L, 2L,
1L, 1L, 1L)), .Names = c("datetime", "outcome"), class = "data.frame",
row.names = c(NA,
-7L))
在嘗試了一些選項之后,這是一個非常簡單的方法。
> mutate(df, v1 = ifelse( outcome > 1, 1, 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.