-1

我想99用仅在 columnsNA中的所有记录替换所有值。我知道如何一次为一列执行此操作,但我想在一个命令中对所有列更有效地执行此操作。ART == '999'L1:L8

样本数据:

df <- structure(list(KARTA = c("02C2H", "02C2H", "02C2H", "02C2H", 
"02C2H", "02C2H", "02C2H", "02C2H", "02C2H", "02C2H", "02C2H", 
"02C2H", "02C2H", "02C7H", "02C7H", "02C7H", "02C7H", "02C7H", 
"02C7H", "02C7H", "02C7H", "02C7H", "02C7H", "02C7H", "02C7H"
), YEAR = c(1997L, 1999L, 2000L, 2001L, 2002L, 2003L, 2005L, 
2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 1997L, 1998L, 2000L, 
2001L, 2002L, 2003L, 2004L, 2006L, 2008L, 2009L, 2010L, 2011L
), ART = c("999", "999", "100", "100", "100", "999", "999", "999", 
"999", "999", "999", "999", "999", "999", "999", "999", "999", 
"999", "999", "999", "999", "999", "999", "999", "999"), L1 = c(99, 
99, 99, 99, 99, 10, 10, 10, 10, 10, 10, 10, 10, 99, 99, 99, 99, 
99, 10, 10, 10, 10, 10, 10, 10), L2 = c(99, 99, 99, 99, 99, 10, 
10, 10, 10, 10, 10, 10, 10, 99, 99, 99, 99, 99, 10, 9, 10, 10, 
10, 10, 10), L3 = c(99, 99, 99, 99, 99, 7, 10, 10, 10, 10, 10, 
10, 10, 99, 99, 99, 99, 99, 10, 10, 10, 10, 10, 10, 10), L4 = c(99, 
99, 99, 99, 99, 10, 10, 10, 10, 10, 10, 10, 10, 99, 99, 99, 99, 
99, 10, 10, 8, 7, 7, 10, 8), L5 = c(99, 99, 99, 99, 99, 5, 8, 
10, 10, 10, 10, 10, 10, 99, NA, 99, 99, 99, 10, 10, 7, 7, 0, 
10, 8), L6 = c(99, 99, 99, 99, 99, 8, 10, 10, 10, 10, 10, 10, 
10, 99, 99, 99, 99, 99, 10, 9, 10, 10, 10, 10, 10), L7 = c(99, 
99, 99, 99, 99, 10, 10, 10, 10, 10, 10, 8, 10, 99, 99, 99, 99, 
99, 10, 10, 10, 10, 10, 10, 10), L8 = c(99, 99, 99, 99, 99, 10, 
10, 10, 10, 10, 10, 10, 10, 99, 99, 99, 99, 99, 10, 10, 6, 10, 
10, 10, 10)), .Names = c("KARTA", "YEAR", "ART", "L1", "L2", 
"L3", "L4", "L5", "L6", "L7", "L8"), row.names = c(161008L, 161009L, 
161010L, 161011L, 161012L, 87055L, 106223L, 128072L, 160909L, 
172583L, 208774L, 45L, 227972L, 161013L, 161014L, 161015L, 161016L, 
161017L, 71813L, 89034L, 139633L, 181266L, 208838L, 97L, 225989L
), class = "data.frame")

如何替换单列('L1')中的值的示例

df[which(df$ART == '999' & df$L1 == '99'), ] <- NA
4

1 回答 1

6

在您的示例中,数据ART始终为 999,但我认为并非总是如此,您只想在 where 的那些行中替换99为,可以这样完成:NAART==999

df$ART[3:5]<-100 #just to give some difference
df[df$ART==999, 4:10][df[df$ART==999,4:10] == 99] <- NA

       KARTA YEAR ART L1 L2 L3 L4 L5 L6 L7 L8
161008 02C2H 1997 999 NA NA NA NA NA NA NA 99
161009 02C2H 1999 999 NA NA NA NA NA NA NA 99
161010 02C2H 2000 100 99 99 99 99 99 99 99 99
161011 02C2H 2001 100 99 99 99 99 99 99 99 99
161012 02C2H 2002 100 99 99 99 99 99 99 99 99
87055  02C2H 2003 999 10 10  7 10  5  8 10 10
...
于 2013-03-21T07:59:51.987 回答