【问题标题】:subselection dataframe子选择数据框
【发布时间】:2011-07-18 00:16:14
【问题描述】:

我想我有一个简单的问题。在我的数据框中,我想创建列 Quality_score 等于的子集:Perfect、Perfect*、Perfect*、Good、Good** 和 Good***

这在我现在的解决方案中:

>Quality_scoreComplete <- subset(completefile,Quality_score == "Perfect" | Quality_score=="Perfect***" | Quality_score=="Perfect****" | Quality_score=="Good" | Quality_score=="Good***" | Quality_score=="Good****") 

有没有办法简化这个方法?喜欢:

methods<-c('Perfect', 'Perfect***', 'Perfect****', 'Good', 'Good***','Good***')
Quality_scoreComplete <- subset(completefile,Quality_score==methods)

谢谢大家,

丽桑

【问题讨论】:

    标签: r dataframe subset


    【解决方案1】:

    你甚至不需要subset,检查:?"["

    Quality_scoreComplete <- completefile[completefile$Quality_score %in% methods,]
    

    已编辑: 基于@Sacha Epskamp 的善意评论:表达式中的== 给出了错误的结果,因此将其更正为%in%。谢谢!

    问题示例:

    > x <- c(17, 19)
    > cars[cars$speed==x,]
       speed dist
    29    17   32
    31    17   50
    36    19   36
    38    19   68
    > cars[cars$speed %in% x,]
       speed dist
    29    17   32
    30    17   40
    31    17   50
    36    19   36
    37    19   46
    38    19   68
    

    【讨论】:

      【解决方案2】:

      一个有效的方法是grepl,它在字符串中搜索一个模式并返回一个逻辑指示它是否存在。您也可以在字符串中使用 | 运算符来指示 OR,并使用 ignore.case 来忽略大小写:

      methods<-c('Perfect', 'Perfect*', 'Perfect*', 'Good', 'Good','Good*')
      
      completefile <- data.frame( Quality_score = c( methods, "bad", "terrible", "abbysmal"), foo = 1)
      
      subset(completefile,grepl("good|perfect",Quality_score,ignore.case=TRUE))
      1       Perfect   1
      2      Perfect*   1
      3      Perfect*   1
      4          Good   1
      5          Good   1
      6         Good*   1
      

      编辑:我现在看到区分大小写不是问题,感谢阅读障碍!您可以简化为:

      subset(completefile,grepl("Good|Perfect",Quality_score))
      

      【讨论】:

      • 哦,我觉得有问题。我在另一个程序中实现了 R,但这个程序没有 regonize |还有其他选择吗?
      • 无法识别该 id 未正确评估 grepl 调用?或者你的意思是你不能输入那个符号?
      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2017-02-06
      • 2021-10-31
      • 2017-08-26
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多