如何根据条件替换多列中的值?

时间:2013-03-21 07:30:57

标签: r replace find criteria

我想将所有值99替换为NA,以便仅在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

1 个答案:

答案 0 :(得分:6)

在您的示例中,数据ART始终为999,但我认为情况并非总是如此,并且您希望仅在99的行中将NA替换为ART==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
...