如何基于data.table中的其他列创建新列? [英] How to create a new column based on other columns in a data.table?
本文介绍了如何基于data.table中的其他列创建新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
DT0 = data.table(x=rep(c(NA,NA,NA)), y=c(0,1,NA), v=c(0, 0, NA), l=c(1,1,1))
DT0
# x y v l
#1: NA 0 0 1
#2: NA 1 0 1
#3: NA NA NA 1
基于前三个列 x
, y
和 v
,我想添加一个新的列,并带有以下输出
Based on the first three cols x
, y
and v
I want to add a new col with following output
#1: No
#2: Yes
#3: NA
如果所有行均为 NA
,则为
NA
.是
(如果其中任何一个为 1
,否则为 0
).我目前的方法是
NA
if all rows are NA
. Yes
if any of them is 1
else 0
. My current approach is
relevant_cols <- c('x', 'y', 'v')
new <- data.table(apply(DT0[, relevant_cols, with=F], 1, function(val) { ifelse(all(is.na(val)), NA_character_, ifelse(any(val == TRUE, na.rm = TRUE), 'Yes', 'No')) }))
DT0[, new:= new]
DT0
# x y v l new
#1: NA 0 0 1 No
#2: NA 1 0 1 Yes
#3: NA NA NA 1 NA
但是,由于实际的 data.table
很大,有没有更好的方法呢?
However, as the actual data.table
is large, is there a better way to do this?
修改:data.table条目通常是非数字的,因此如果我能提供比使用 pmax
例如
,
Often the data.table entries are non-numeric hence it would be quite helpful if I can have a more general solution than using pmax
e.g.
,
DT = data.table(x=rep(c(NA,NA,NA)), y=c('No','Yes',NA), v=c('No', 'No', NA), l=c(1,1,1))
DT
# x y v l
#1: NA No No 1
#2: NA Yes No 1
#3: NA NA NA 1
推荐答案
这里是一个选择:
DT[, new := ifelse(rowSums(.SD == "Yes", na.rm = T) > 0,
'Yes',
ifelse(rowSums(is.na(.SD)) != ncol(.SD), "No", NA))
, .SDcols = x:v]
# x y v l new
#1: NA No No 1 No
#2: NA Yes No 1 Yes
#3: NA NA NA 1 NA
这篇关于如何基于data.table中的其他列创建新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文