问题上下文:通过将chr转换为numeric来替换数据帧中的chr变量。使用一个函数将chr转换为numeric,然后在传递要转换为numeric的df_credit_status$length_of_service时应用(),并更新相同的数据框列,例如df_credit_status$length_of_service。
我定义了这个函数和apply()函数。
数据帧列字段: df_credit_status$length_of_service是chr,对于这次更新,我可能需要创建一个新字段,然后在更改数据类型后将结果移动/复制到df_credit_status$length_of_service。
fun_year <- function(length) { as.numeric(gsub("[A-Za-z]|[[:punct:]]|\\s+", "", length))}
df_credit_status$length <- apply(df_credit_status$length_of_service, FUN=fun_year)apply()中的错误是dim(x)必须具有正的长度。
dput()包含来自df_credit_status$length_of_service的数据
"< 1 year", "2 years", "3 years", "4 years", "5 years", "6 years", "7 years", "8 years", "9 years", "10+ years"发布于 2020-03-10 05:11:04
因为您创建的函数可以很好地处理向量,所以我们不需要使用sapply
df_credit_status$length <- fun_year(df_credit_status$lenght_of_service)返回:
lenght_of_service length
1 < 1 year 1
2 2 years 2
3 3 years 3
4 4 years 4
5 5 years 5
6 6 years 6
7 7 years 7
8 8 years 8
9 9 years 9
10 10+ years 10https://stackoverflow.com/questions/60608297
复制相似问题