您好我正在尝试在我的数据集列中将所有非NA值设置为1。以下是一些示例数据:
structure(list(ID = c(1, 1, 1, 1, 2, 3, 4, 4), match = structure(c(NA,
10227, 10227, 10957, NA, 11323, NA, 11323), class = "Date"),
actual.date = structure(c(10135, 10258, 11808, 11808, 10773,
13027, 13269, 12086), class = "Date")), .Names = c("ID",
"match", "actual.date"), row.names = c(NA, -8L), class = "data.frame")
ID match actual.date
1 1 <NA> 1997-10-01
2 1 1998-01-01 1998-02-01
3 1 1998-01-01 2002-05-01
4 1 2000-01-01 2002-05-01
5 2 <NA> 1999-07-01
6 3 2001-01-01 2005-09-01
7 4 <NA> 2006-05-01
8 4 2001-01-01 2003-02-03
对于&#39;匹配&#39;列我想将所有非NA&#39等于1。
答案 0 :(得分:1)
通常你会使用dat$match[!is.na(dat$match)] <- 1
之类的东西,但这会导致Date列出错。您可以使用ifelse
:
dat$match <- ifelse(is.na(dat$match), NA, 1)
dat
# ID match actual.date
# 1 1 NA 1997-10-01
# 2 1 1 1998-02-01
# 3 1 1 2002-05-01
# 4 1 1 2002-05-01
# 5 2 NA 1999-07-01
# 6 3 1 2005-09-01
# 7 4 NA 2006-05-01
# 8 4 1 2003-02-03
如果您想制作二进制列(如您在原始问题的评论中所示),您可以这样做:
dat$match <- !is.na(dat$match)
dat
# ID match actual.date
# 1 1 FALSE 1997-10-01
# 2 1 TRUE 1998-02-01
# 3 1 TRUE 2002-05-01
# 4 1 TRUE 2002-05-01
# 5 2 FALSE 1999-07-01
# 6 3 TRUE 2005-09-01
# 7 4 FALSE 2006-05-01
# 8 4 TRUE 2003-02-03