I am using the "ifelse" function in R and I am trying to create two new columns (i.e. x1 and x2) from a large data set similar to the following dataframe
df <-
structure(
list(
id = c(1L, 2L, 3L, 4L,5L),
date1 = c("1/4/2004", "3/11/2004", "NA", "13/10/2004","11/3/2003"),
date2 = c("8/6/2002", "11/5/2004", "3/5/2004","25/11/2004","21/1/2004"),
s1=c(1,2,1,"NA","NA"),
date3=c("NA", "NA", "18/2/2006", "NA","NA"),
s2=c("NA","NA",2,"NA","NA")
),
.Names = c("id", "date1","date2","s1","date3","s2"),
class = "data.frame",
row.names = c(NA,-5L),
col_types = c("numeric", "date","date","numeric","date","numeric")
)
The new column, x1 is expected to have a value of 3 if date1 is not "NA" and the corresponding cell of s1 has NA, otherwise x1 should be the value of s1. Similarly, x2 is expected to have a value of 3 if date1 is not "NA" and the corresponding cell of s2 has NA, otherwise x2 should be the value of s2.
To achieve this, I used the following codes
df$x1<-ifelse(!is.na(df$date1) & (df$s1=="NA"),d,df$s1)
df$x2<-ifelse(!is.na(df$date1) & (df$s2=="NA"),d,df$s2)
This code works on the above dataframe but it does not work on the large data set, meanwhile it does not report any error. By this, I mean the code runs on the large data set without errors but it does not perform the expected function. Please, I would like to know why this problem is occurring and how it could be fixed. I appreciate any help on this.
Aucun commentaire:
Enregistrer un commentaire