R在课程日期插入错误的年份

时间:2016-04-16 06:23:23

标签: r date

我需要将此行插入到我的数据框中:

new_row<-c("015-06-17","1+-07-24",0,1,">=10")

如何将这个错误的日期放在Class Date的BirthDate和MarriageDate列中?

现有数据框:

BirthDate        MarriageDate      Sons        Daugther      Time     

  1952-10-05       1980-11-03        1              0           <10
  1980-06-14       2002-05-20        0              2           >=10

预期数据框:

BirthDate        MarriageDate      Sons        Daugther      Time     

  1952-10-05       1980-11-03        1              0           <10
  1980-06-14       2002-05-20        0              2           >=10
  015-06-17         1+-07-24         0              1           >=10

我需要将它们放在数据框中,以便在插入后更正它们。

1 个答案:

答案 0 :(得分:0)

“df1”中的列类型尚不清楚。假设所有都是'字符',那么

rbind(df1, as.list(new_row))

或者如果'Sons'和'Daughther'是numeric,那么我们必须将vector元素更改为各自的类。

lst <- lapply(new_row, function(x) { 
              x1 <- type.convert(x)
              if(is.factor(x1)) as.character(x1) else x1})

df2 <- rbind(df1, lst)
df2
#   BirthDate MarriageDate Sons Daugther Time
#1 1952-10-05   1980-11-03    1        0  <10
#2 1980-06-14   2002-05-20    0        2 >=10
#3  015-06-17     1+-07-24    0        1 >=10

str(df2)
#'data.frame':   3 obs. of  5 variables:
#$ BirthDate   : chr  "1952-10-05" "1980-06-14" "015-06-17"
#$ MarriageDate: chr  "1980-11-03" "2002-05-20" "1+-07-24"
#$ Sons        : int  1 0 0
#$ Daugther    : int  0 2 1
#$ Time        : chr  "<10" ">=10" ">=10"