r - 如何在 R 中自动化这个简单的条件列操作?
问题描述
我有一个如下所示的数据框:
tibble(term = c(
rep("a:b", 2),
rep("b:a", 2),
rep("c:d", 2),
rep("d:c", 2),
rep("g:h", 2),
rep("h:g", 2)
))
我想在此数据框中添加一个额外的列,该列对于具有相同字符但反转并由“:”分隔的任何对具有相同的值(即 a:b 和 b:a 将以相同的方式编码; 与 c:d 和 d:c 以及所有其他对类似)。
我想到了以下内容:
%>%
mutate(term_adjusted = case_when(grepl("a:b|b:a", term) ~ "a:b"))
但是我的数据集中有大量这样的对,并且想要一种自动化的方法,因此我的问题是:
我怎样才能自动执行此操作而不必分别为每一对进行硬编码?
谢谢!
解决方案
怎么样:
libary(dplyr)
your_data %>%
mutate(term_adjusted = term %>%
strsplit(":") %>%
purrr::map_chr(~ .x %>%
sort() %>%
paste(collapse = ":")))
基础 R 选项
your_data$term_adjusted <- your_data$term |>
strsplit(":") |>
lapply(sort) |>
lapply(paste, collapse = ":") |>
unlist()
要么返回:
# A tibble: 12 x 2
term term_adjusted
<chr> <chr>
1 a:b a:b
2 a:b a:b
3 b:a a:b
4 b:a a:b
5 c:d c:d
6 c:d c:d
7 d:c c:d
8 d:c c:d
9 g:h g:h
10 g:h g:h
11 h:g g:h
12 h:g g:h
推荐阅读
- python - Python 日志记录和动态日志文件名
- python - PyQt5 QGroupBox 与 QCheckBox - 关闭自动禁用
- php - 我从 PHP PDO 中的数据库中得到�三角形中的问号和�
- javascript - 基于另一个在 vue 3 中计算的变化计算
- xcode - 与名为 com.apple.fonts 的服务的连接在 xcodebuild -resolvePackageDependencies 上无效
- r - 通过循环 ggplot 创建多个绘图时动态分配绘图对象名称(按索引)
- r - 从某些字符串中删除 NA 并将其粘贴到一个 data.frame 中
- vba - 如何获得精确格式的 MS word 段落使用 VBA 复制和粘贴
- javascript - 添加绝对定位的伪元素时移动表格边框
- reactjs - 为什么反应路线在 nextjs 中不起作用?