R中OR函数(|)的正确用法是什么?

时间:2017-05-29 09:19:33

标签: r ggplot2

我正在尝试使用ggplot绘制两组数据,并且尝试在此代码行中使用OR函数时遇到问题。

statistics2 <- statistics2[startsWith(as.character(statistics2$Series_Name), prefix = "Health expenditure per capita"), ]

根据我的理解,这是正确的:

statistics2 <- statistics2[startsWith(as.character(statistics2$Series_Name), prefix = "Health expenditure per capita"|"Life expectancy at birth, total (years)"), ]

但是返回错误:

Error in "Health expenditure per capita" | "Life expectancy at birth, total (years)" : 
  operations are possible only for numeric, logical or complex types

有人可以帮助我理解问题是什么,从我在其他地方读到的,我对OR(|)函数的使用是正确的。

提前致谢,

3 个答案:

答案 0 :(得分:1)

prefix = "Health expenditure per capita" | prefix = "Life expectancy at birth, total (years)")

添加&#39;前缀=&#39;另一方面。

答案 1 :(得分:0)

./config/initializers/session_store.rb允许您使用 module SessionPath extend ActiveSupport::Concern def self.included(base) base.class_eval do alias_method :set_cookie_original, :set_cookie alias_method :set_cookie, :set_cookie_extended end end def set_cookie_extended(request, session_id, cookie) cookie[:path] = Rails.application.config.x.base_url #or what you need set_cookie_original(request, session_id, cookie) end end ActionDispatch::Session::AbstractStore.send(:include, SessionPath) 的向量,因此以下内容可以使用

startsWith

答案 2 :(得分:0)

prefix中的startsWith(x, prefix)参数是一个字符向量。当你写prefix = "foo"时,这是一个长度为1且等于prefix = c("foo")的字符向量。

prefix向量被&#34;回收&#34;,直到x中的每个元素都匹配一次。对于长度为1的prefix向量,prefix中的单个元素与x的所有元素匹配:

startsWith(x = c("one", "two", "three"), prefix = "t")
[1] FALSE  TRUE  TRUE

如果前缀包含多个元素,prefix的元素将与x的元素匹配,直到x的所有元素都匹配为止:

startsWith(x = c("one", "two", "three"), prefix = c("t", "o"))
# "one" "two" "three"
# "t"   "o"   "t"     <= prefix is repeated until end of x
[1] FALSE FALSE  TRUE

如果您想将x的每个元素与prefix的每个元素相匹配,则必须分别为每个前缀元素运行startsWith

startsWith(x = c("one", "two", "three"), prefix = "t") | startsWith(x = c("one", "two", "three"), prefix = "o")
[1] TRUE TRUE TRUE

因此,问题的解决方案如下:

statistics2 <- statistics2[
    startsWith(as.character(statistics2$Series_Name), prefix = "Health expenditure per capita")
    |
    startsWith(as.character(statistics2$Series_Name), prefix = "Life expectancy at birth, total (years)"),
]