Как стать автором
Обновить

Комментарии 3

ifelse весьма бестолковая в плане производительности штука, смотрим варианты (цифры с моего компа 8E6 элементов, ускорение относительно скорости ifelse варианта [2.261 сек])

Преалокация + прямое присваивание по условию: х8
system.time({
  output <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  res <- character(nrow(df))
  res[!output]  = "less_than_4"
  res[output] = "greater_than_4"
  df$output <- output
})

Трюк для уменьшения количества присваиваний: х10

system.time({
  output <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  res <- rep("less_than_4",nrow(df))
  res[output] = "greater_than_4"
  df$output <- output
})


Не выпендриваться и не использовать строки: х27

system.time({
  output <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  df$output <- output
})


Делаем имена фактором, но не знаем как оно работает: x1.5

system.time({
  output <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  output <- as.factor(output)
  levels(output) <- c("less_than_4", "greater_than_4")
  df$output <- output
})


Имена фактором но с R знакомы: x21

system.time({
  output <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  output <- output+1L
  levels(output) <- c("less_than_4", "greater_than_4")
  class(output) <- "factor"
  df$output <- output
})
library(dplyr)

system.time({
df < — df %>%
mutate(col5 = ifelse((col1 + col2 + col3 + col4) > 4, «greater_than_4», «lesser_than_4»))
})

> dim(df)
[1] 248832 5

user system elapsed
0.10 0.02 0.13

i5@1.70Ghz. CRAN ждет вас ;)
А с magrittr можно еще проще:

df %<>% mutate(col5 = ......)
Зарегистрируйтесь на Хабре, чтобы оставить комментарий