2016-12-27 85 views
0

我有一欄:重命名標題

 id father mother sex birthdate.x birthdate.y 
1 john  0  0 1  <NA>   NA 
2 mari  0  0 2  01/01/1996 NA 
3 paul  0  0 2  <NA>  01/01/1995 
4 ralf  0  0 2  <NA>   NA 
5 kimb  0  0 2  01/01/1997 NA 

每次我用它來「合併」 birthdate.xbirthdate.y,它給了我一個簡單的數字時間和金錢。

df1$birthdate.x <- ifelse(is.na(df1$birthdate.y), df1$birthdate.x, df1$birthdate.y) 
df1$birthdate.y <- NULL 
names(df1)[names(df1)=="birthdate.x"] <- "birthdate" 

     id  father mother sex birthdate 
1 john  0  0  1 NA 
2 mari  0  0  2 2 
3 paul  0  0  2 1 
4 ralf  0  0  2 NA 
5 kimb  0  0  2 3 
+2

'ifelse'失去屬性做到這一點;在這種情況下是因子標籤。轉換爲字符,它會起作用。 (具有諷刺意味的是,如果你轉換成Date類,你將會遇到同樣的問題。) – alistaire

+0

我如何轉換成角色? –

+0

'df1 $ birthdate.x < - as.character(df1 $ birthdate.x)'併爲'birthdate.y'重複,或直接在'ifelse'中執行,即'df1 $ birthdate < - ifelse(is.na (df1 $ birthdate.y),as.character(df1 $ birthdate.x),as.character(df1 $ birthdate.y))' – alistaire

回答

1

我們可以pmax

transform(df1, birthdate = pmax(as.character(birthdate.x), 
      as.character(birthdate.y), na.rm = TRUE))[-(5:6)] 
# id father mother sex birthdate 
#1 john  0  0 1  <NA> 
#2 mari  0  0 2 01/01/1996 
#3 paul  0  0 2 01/01/1995 
#4 ralf  0  0 2  <NA> 
#5 kimb  0  0 2 01/01/1997