首页 > 解决方案 > R:错误在哪里:if 语句覆盖多列

问题描述

我有以下数据表,其中包含“字符”类的列

dt <- data.table(V1 = c("0", "1", "1/2", "4"), V2 = c("1/2", "3/4", "", ""))

我只想在第二列和第一列自然数中包含所有分数。我想出了以下解决方案:

if(str_detect(new$V1, "/")){
  new$V2 <- new$V1
  new$V1 <- 0
}

并且还尝试将它嵌入到一个函数中并用sapply.

FractionExtraction <- function(x, y) {
  if(str_detect(x, "/")){
  y <- x 
  } else {y <- y}
  y
}

dt$V2  <- sapply(dt$V1, FractionExtraction, dt$V2)

我还尝试在 if 语句中使用 %in%,或者用相等符号交换“<-”,但我仍然会收到以下错误

Warning message:
In if (str_detect(new$V1, "/")) { :
  the condition has length > 1 and only the first element will be used

理想情况下,输出如下所示:

> dt
   V1  V2
1:  0 1/2
2:  1 3/4
3:  0 1/2
4:  4    

任何帮助将不胜感激!

标签: rif-statementsapply

解决方案


dplyr

dt %>% 
  mutate(V2 = ifelse(str_detect(V1, "/"), V1, V2),
         V1 = ifelse(str_detect(V1, "/"), 0, V1))
  V1  V2
1  0 1/2
2  1 3/4
3  0 1/2
4  4    

推荐阅读