2017-04-23 78 views
0

我试图替换此表中显示的值。根据条件替换值

  • 如果ANABC设置AUnknown
  • 如果ANABC得到了一个值,设置AMissing Value

 A   B  C 
1 NA  NA NA 
2 NA  200 NA 


       A  B  C  
1 NotImportant  NA  NA 
2  Unknown  200  NA  

我试过一番,

if(is.na(ColumnA)) ColumnB[is.na(ColumnB)] <= "Not Important" 
if(is.na(ColumnA)) ColumnB[!is.na(ColumnB)] <= "Unknown" 

,但我没有得到任何结果。

有人能帮我解决这个问题吗?我希望我能很好地描述我的问题。

回答

0

你可以试试这个地方df是你的数据:

df[rowSums(is.na(df))==3,]$A <- "NotImportant" 
df[with(df, is.na(A) & (!is.na(B) | !is.na(C))),]$A <- "Unknown" 

#    A B C 
#1 NotImportant NA NA 
#2  Unknown 200 NA 
0

下面介绍如何在使用做case_whendplyr

df <- structure(list(A = c(NA, NA), B = c(NA, 200L), C = c(NA, NA)), .Names = c("A", 
"B", "C"), class = "data.frame", row.names = c("1", "2")) 

library(dplyr) 
df%>% 
mutate(A=case_when(
is.na(.$A)&is.na(.$B)&is.na(.$C) ~ "Not Important", 
is.na(.$A)&(is.na(.$B)|is.na(.$C)) ~ "Unknown") 
) 

       A B C 
1 Not Important NA NA 
2  Unknown 200 NA 
1
df$A <- ifelse(!is.na(df$A), 
         df$A, 
         ifelse(is.na(df$B) & is.na(df$C), 
          "Not Important", 
          "Missing Value")) 

# A B C 
# 1 Not Important NA NA 
# 2 Missing Value 200 NA