R -对单列逐行应用自定义函数



我创建了一个自定义函数,希望将其逐行应用于数据框的单个列,然后将其分配回原始列

自定义函数如下,目的是在excel文件中固定日期。

format_dates = function(x) {
x = trimws(x)
if ( grepl('/', x, fixed=TRUE) ) {
as.Date(x, tryFormats = c("%d/%m/%Y", "%m/%d/%Y"))
} else {
tryCatch(
{ as.Date(as.integer(x), origin='1899-12-30') },
warning=function(x) { return( NA ) 
} )
}
}

必须逐行执行此操作。我已经搜索过了,我已经看到很多回复使用lapply, apply,和sapply,但他们不工作。作为一个例子,我尝试:

df$Child_Date_of_Birth = apply(df$Child_Date_of_Birth, 2, format_dates)

结果为

Error in apply(df$Child_Date_of_Birth, 2, format_dates) : 
dim(X) must have a positive length

这是令人沮丧的,因为在Pandas中你可以简单地运行

df['Child_Date_of_Birth'] = df['Child_Date_of_Birth'].apply(format_dates)

但是在R中这变成了最晦涩的东西??

谁能指点我一下……非常感谢

一个示例数据将是有用的,但我认为你可以尝试sapply:

df$Child_Date_of_Birth <- sapply(df$Child_Date_of_Birth, format_dates)

最新更新