[英]data.table way to create new column based on on other columns
我正在編譯一些網絡研討會的結果,並有一個由三列組成的data.table
- 電子郵件地址,如果他們參加了網絡研討會並且他們聽了錄音( emails
、 webinar
、 recording
):
# recycling is intentional here
> dat <- data.table(emails = letters[1:10], webinar = c('yes', 'Yes', 'no', 'yes'), recording = c('Yes', NA, 'NA'))
> dat
emails webinar recording
1: a yes Yes
2: b Yes <NA>
3: c no NA
4: d yes Yes
5: e yes <NA>
6: f Yes NA
7: g no Yes
8: h yes <NA>
9: i yes NA
10: j Yes Yes
如果webinar
或recording
為Yes
或yes
,我想添加一個值為 2 的新列score
,否則為 1。
使用上述示例數據,我可以通過以下方式獲得所需的輸出:
> dat[, score := ifelse(tolower(webinar) == 'yes' | tolower(recording) == 'yes', 2, 1), by = .(emails)]
> dat
emails webinar recording score
1: a yes Yes 2
2: b Yes <NA> 2
3: c no NA 1
4: d yes Yes 2
5: e yes <NA> 2
6: f Yes NA 2
7: g no Yes 2
8: h yes <NA> 2
9: i yes NA 2
10: j Yes Yes 2
但是,在我的實際數據集上,相同的邏輯失敗了:
emails webinar recording score
1: email_redacted1 No <NA> NA
2: email_redacted2 Yes <NA> TRUE
3: email_redacted3 No <NA> NA
4: email_redacted4 Yes <NA> TRUE
5: email_redacted5 No <NA> NA
---
204: email_redacted6 No <NA> NA
205: email_redacted7 No <NA> NA
206: email_redacted8 No <NA> NA
207: email_redacted9 Yes <NA> TRUE
208: email_redacted0 No <NA> NA
出於隱私原因,我手動刪除了電子郵件,但執行此操作的數據集是data.table
並且與上面的示例具有相同的 3 列。
我確實在控制台中收到了一些警告:
50: In `[.data.table`(retdat, , `:=`(score, ifelse(tolower(webinar) == ... :
Group 88 column 'score': 2.000000 (type 'double') at RHS position 1 taken as TRUE when assigning to type 'logical'
我目前的解決方法如下:最初將score
設置為 1,然后在滿足任一條件時使用data.table
“i”將其設置為 2:
dat$score <- 1
dat[tolower(webinar) == 'yes' | tolower(recording) == 'yes', score:= 2]
問題:
data.table
方式是什么(與示例數據一起顯示)您的示例與您的實際數據集不同,因為您在ifelse
的條件始終為TRUE
或FALSE
但在實際數據集中,它也有NA
值( TRUE | NA = TRUE, FALSE | NA = NA
)。 檢查?ifelse
以獲取有關NA
和結果類型的更多詳細信息。 基本上這發生了:
tolower(webinar) == 'yes' | tolower(recording) == 'yes'
tolower(webinar) == 'yes' | tolower(recording) == 'yes'
是NA
NA
在ifelse
函數將返回NA
的結果其位置NA
你的結果向量將是logical
您也可以刪除by
,這種操作不需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.