给定条件(使用%>%),将生成不在NA列A中的值。

mutate_at(vars(-columnA), funs(((function(x) {
if (is.logical(x))
  return(x)
else if (!is.na(as.numeric(x)))
  return(as.numeric(x))
else
  return(NA)
})(.))))


如何使用mutate_at和嵌套ifelse获得相同的结果?

例如,这不会产生相同的结果:

mutate_at(vars(-columnA),funs(ifelse(is.logical(.),.,
ifelse(!is.na(as.numeric(.)),as.numeric(.),NA))))


更新(2018-1-5)

这个问题的意图是令人困惑的,部分原因是我对传递给函数的东西有误解。

这是我打算写的:

mutate_at(vars(-columnA), funs(((function(x) {
  for(i in 1:length(x))
  {
    if(!is.na(as.numeric(x[i])) && !is.logical(x[i]))
    {
      x[i] <- as.numeric(x[i]);
    }
    else if(!is.na(x[i]))
    {
      x[i] <- NA
    }
  }
  return(x)
})(.))))


这是一个更好的解决方案:

mutate_at(vars(-columnA), function(x) {
  if(is.logical(x))
      return(x)

  return(as.numeric(x))
})


在这种情况下,ifelse可能不合适,因为ifelse返回的值与条件的形状相同,即1个逻辑元素。在这种情况下,is.logical(。)的条件结果的长度为1,因此返回值将是传递给该函数的列的第一个元素。

更新(2018-1-6)

使用ifelse,这将按原样返回包含逻辑值或NA的列,否则将as.numeric应用于列。

mutate_at(vars(-columnA),funs(
ifelse(. == TRUE | . == FALSE | is.na(.),.,as.numeric(.))))

最佳答案

主要问题是

else if (!is.na(as.numeric(x)))
     return(as.numeric(x))


if/else适用于vectorlength1。如果应用该功能的lengthvector/column大于1,则最好使用ifelse。在上面的代码中,!is.na(as.numeric(x))返回长度大于1的逻辑vector(假设数据集中的行数大于1)。使它起作用的方法是用all/any包装(取决于我们需要的内容)

f1 <- function(x) {
    if (is.logical(x))
         return(x)
      else if (all(!is.na(as.numeric(x))))
         return(as.numeric(x))
          else
       return(x) #change if needed
}

df1 %>%
    mutate_all(f1)


数据

set.seed(24)
df1 <- data.frame(col1 = sample(c(TRUE, FALSE), 10, replace = TRUE),
     col2 = c(1:8, "Good", 10), col3 = as.character(1:10),
 stringsAsFactors = FALSE)

关于r - 将mutate_at与嵌套ifelse一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48105066/

10-12 17:47