清除R中的列数据

清除R中的列数据,r,R,您好,我编写此函数是为了清理R中的数据: periodCleanse <- function(x) { if (x == ""){ return (""); } else if (substr(x, nchar(x), nchar(x)) == "M"){ return(30*as.numeric(substr(x, 1, nchar(x)-1))); } else if (substr(x, nchar(x), nc

您好,我编写此函数是为了清理R中的数据:

periodCleanse <- function(x) {
    if (x == ""){
        return ("");
    }
    else if (substr(x, nchar(x), nchar(x)) == "M"){
        return(30*as.numeric(substr(x, 1, nchar(x)-1)));
    }
    else if (substr(x, nchar(x), nchar(x)) == "Y"){
        return(365*as.numeric(substr(x, 1, nchar(x)-1)));
    }
    else if (substr(x, nchar(x), nchar(x)) == "D"){
        return (as.numeric(substr(x, 1, nchar(x)-1)));
    }
}
我想打电话

df$period <- periodCleanse(df$period))

什么也没发生。我该怎么办?

您的函数接受向量(数据帧的列),但只返回一个值。您可以通过
将函数应用于向量的每个元素:
sappy(df$period,periodclease)
来解决这个问题。请注意,仅当列是字符向量而不是因子时,
nchar
才起作用


触发此警告是因为您正在获取布尔向量(从
x==“”
),并在
if
条件下使用它;R将只使用第一个元素,并生成警告,因为它可能不是您想要的。另一种方法是,可以在向量化时链接多个
ifelse
调用,但这在很多情况下都会变得很麻烦。

我只需要创建一个向量化函数,它既可以避免编写无休止的
if
调用,又可以在循环中运行(
sapply

2
df$period <- periodCleanse(df$period))
Warning message:
In if (x == "") { :
  the condition has length > 1 and only the first element will be used
periodCleanse2 <- function(x){
  matchDat <- data.frame(A = c("M", "Y", "D"), B = c(30, 365, 1)) # You can take that part out of the function for improving speed
  indx <- gsub("\\d", "", x)
  indx2 <- as.numeric(gsub("[A-Z]", "", x))
  matchDat$B[match(indx, matchDat$A)] * indx2
}

periodCleanse2(df$period)
## [1]   90 1825   NA    1  210