r - 根据数据框 R 中的另一列更改列中的值
问题描述
df ex:
# A tibble: 20 x 2
Autoswing `Duration(seconds)`
<chr> <dbl>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✗ Inf
15 ✗ 14
16 ✗ Inf
17 ✗ Inf
18 ✗ Inf
19 ✗ Inf
20 ✗ Inf
如果 Duration(seconds) 为 inf,我想在 Autoswing 中将所有 ✗ 更改为 ✓。我试图使用 if 语句
解决方案
我们可以使用base R
方法,即检查无限值is.infinite
来创建一个逻辑向量并进行赋值
df$Autoswing[is.infinite(df$`Duration(seconds)`)] <- "✓"
-输出
> df
# A tibble: 20 × 2
Autoswing `Duration(seconds)`
<chr> <dbl>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✓ Inf
15 ✗ 14
16 ✓ Inf
17 ✓ Inf
18 ✓ Inf
19 ✓ Inf
20 ✓ Inf
或与data.table
library(data.table)
setDT(df)[is.infinite(`Duration(seconds)`), Autoswing := "✓"]
或dplyr
使用replace
library(dplyr)
df %>%
mutate(Autoswing = replace(Autoswing, is.infinite(`Duration(seconds)`), "✓"))
# A tibble: 20 × 2
Autoswing `Duration(seconds)`
<chr> <dbl>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✓ Inf
15 ✗ 14
16 ✓ Inf
17 ✓ Inf
18 ✓ Inf
19 ✓ Inf
20 ✓ Inf
数据
df <- structure(list(Autoswing = c("✗", "✗", "✗", "✗", "✗",
"✗", "✗", "✗", "✗", "✗", "✗", "✗", "✗", "✗",
"✗", "✗", "✗", "✗", "✗", "✗"), `Duration(seconds)` = c(4,
5, 7, 6, 8, 9, 11, 16, 16, 8, 12, 15, 10, Inf, 14, Inf, Inf,
Inf, Inf, Inf)), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA,
-20L))
推荐阅读
- apache-flink - Flink - 手动删除键
- git - GitHub 推送失败,RPC 失败;curl 55 SSL_write() 返回 SYSCALL,errno = 32
- python - 无法在 OpenCV Python 中读取 MP4 和 avi 文件
- javascript - 使用 iframe 和 jquery 对话框时缺少实例数据 Datepicker
- python-3.x - 如何使nohup进程活着?
- node.js - 猫鼬 findOneAndUpdate 不从数组中删除对象
- google-chrome - 检查*域名*中是否有错字
- google-cloud-platform - Google BigQuery 的资源窗口
- python - 系统找不到指定的文件 - Python语音识别
- c# - “参数”是一个“类型”,在给定的上下文中无效