簡體   English   中英

將列中的所有非NA設置為1

[英]Set all non-NAs in column to 1

嗨,我正在嘗試將數據集中的所有非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

對於“匹配”列,我要將所有非NA都設置為等於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

暫無
暫無

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

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