r - 如何使用 dplyr 中的 select 函数返回结果?
问题描述
我的数据在表格(我称之为表格)中看起来像这样:
第 1 列:(苹果 A、苹果 B、香蕉 A、香蕉 B)
第 2 列:(1、2、3、4)
我想创建一个以 A 结尾的所有第 1 列和所有以 B 结尾的第 1 列的向量。我正在使用:A<-select(table, ends_with("A"))
,试图获得“Apples A”Apples B“的值。相反,我得到一个具有 4 个观察值和 0 个变量的数据框。我确实尝试A<-grepl("A", fixed=TRUE, table$column1)
过,但这给了我真、假、真、假,这不是我想要的。我可能遗漏了一些愚蠢明显的东西,不是吗?
解决方案
使用 stringr 处理字符串:
$ 表示以结尾,^ 表示以开头
library(stringr)
df %>% filter(str_detect(column_1, "A$"))
column_1 column_2
1 Apples A 1
2 Bananas A 3
# or :
> df %>% filter(str_detect(column_1, "^Bananas"))
column_1 column_2
1 Bananas A 3
2 Bananas B 4
# or use both at the same time:
> df %>% filter(str_detect(column_1, "^Bananas A$"))
column_1 column_2
1 Bananas A 3
############ then use select to only select the first column: column_1
df %>% filter(str_detect(column_1, "A$")) %>% select(column_1)
# same as:
df %>% filter(str_detect(1, "A$")) %>% select(1)
########### Finally to store it in a vector "myvector" you can use pull()
df %>% filter(str_detect(1, "A$")) %>% select(1) %>% pull(1) -> myvector
推荐阅读
- ios - 如何使用 SPM 托管在私有仓库中的 .zip 格式的二进制或 xcFramework
- java - 用于使用 Kotlin/Java 设置的事件的 Google 日历 api 监视方法
- javascript - 带参数调用 Testcafe 客户端函数
- c - (char) 在 ((unsigned char) ~0 >> 1) 之前的作用是什么?
- flutter - flutter moor - 更新表格特定行中的特定列
- .net - .NET 框架 4.8 是否预装在 Windows 11 上
- html - 如何处理这种类型的 JSON 数据?(对象对象)
- reactjs - 状态没有立即更新功能组件
- javascript - 使用 Leaflet 动态加载多个外部 GeoJson 数据文件并动态调用多个图层
- c++ - QML darag&drop 错误“grabToImage:项目的窗口不可见”