数据过滤器基于对象和变量使用R



我正在尝试从变量中筛选对象。这是我的数据;

head(DfUse)
InstanceType  ProductDescription      SpotPrice       ymd_hms(Timestamp)
<chr>                 <chr>           <dbl>                    <chr> 
1   a1.2xlarge  Linux/UNIX  0.0671  06:17:23
2   a1.2xlarge  Red Hat Enterprise Linux    0.1971  06:17:23
3   a1.2xlarge  SUSE Linux  0.2171  06:17:23
4   a1.4xlarge  Linux/UNIX  0.1343  12:15:54
5   a1.4xlarge  Red Hat Enterprise Linux    0.2643  12:15:54
6   a1.4xlarge  SUSE Linux  0.2843  12:15:54

数据的维度是

dim(DfUse)
[1] 10078     4

数据集结构

str(DfUse)
'data.frame':   10078 obs. of  4 variables:
$ InstanceType      : chr  "  a1.2xlarge" "  a1.2xlarge" "  a1.2xlarge" "  a1.4xlarge" ...
$ ProductDescription: chr  "  Linux/UNIX" "  Red Hat Enterprise Linux" "  SUSE Linux" "  Linux/UNIX" ...
$ SpotPrice         : num  0.0671 0.1971 0.2171 0.1343 0.2643 ...
$ ymd_hms(Timestamp): chr  "06:17:23" "06:17:23" "06:17:23" "12:15:54" ...

当我尝试过滤时

filter(DfUse, InstanceType == 'a1.2xlarge')
0 rows

请帮助筛选数据集。我想将所有过滤后的值按其他变量分组。

从数据集结构来看,数据中似乎有一些空白。您可以使用trimws删除它。

dplyr::filter(DfUse, trimws(InstanceType) == 'a1.2xlarge')

带基座Rsubset-

subset(DfUse, trimws(InstanceType) == 'a1.2xlarge')

最好通过删除开头或结尾的空白来转换所有character列(以避免任何进一步的问题(,然后执行filter

library(dplyr)
DfUse %>%
mutate(across(where(is.character), trimws)) %>%
filter(InstanceType == "a1.2xlarge")

最新更新