r - 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
任何帮助将不胜感激!
解决方案
与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
推荐阅读
- awk - 提取 aws 凭证文件的键值对
- python - python检查字符串是否包含具有某种格式的“单词”
- java - Java 抽象原始数组加法
- python - 如何提取此 span 标签中括号内的数字?
- r - 将 lm 与 summarise/across 一起应用时丢失列名
- android - Flutter ThemeData 中 FAB 图标的颜色属性
- java - 杰克逊反序列化 - 错误的身体类型成功反序列化
- javascript - 如何在 javascript 文件上运行 php 加密功能?
- php - Laravel 8 - 选择特定值时自动更新表单字段
- python - 在 pandas df.stack 之后用最后一个已知值填充列