0

I was asked to import a csv file in R and to insert lines for 2 people with the sex and date of birth.

Existing dataframe:

Sex                     BirthDate

1                       05/10/1952           
1                       14/06/2004                         
2                       21/11/1963 

In the existing dataframe date of birth is in class "factor".

class(BirthDate)
[1] "factor"

I need to insert:

person 1 : 2, 20/10/1980
person 2 : 1, 21/02/1970

I tried:

b1 <- rbind(
    dataf1,
    c("2", as.factor("20/10/1980")),
    c("1", as.factor("21/02/1970"))
)

but I have NA in BirthDate

How to insert dates without changing the existing dataframe?

nrussell
  • 18,382
  • 4
  • 47
  • 60
E.bl
  • 27
  • 4

1 Answers1

1

Its best to use the as.is argument when using read.csv and then convert the date variable into a date after the read:

my.data.frame <- read.csv(<filepath>, as.is=TRUE)
my.data.frameBirthDate <- as.Date(my.data.frameBirthDate, format="%d/%m/%Y")

You can then append the new data and not worry about the factors issue:

my.data.frame <- rbind(my.data.frame, 
                   data.frame("Sex"=c(2,1), 
                   "BirthDate"=as.Date(c("20/10/1980", "21/02/1970"), format="%d/%m/%Y")))
lmo
  • 37,904
  • 9
  • 56
  • 69