【问题标题】:How can I write logical Column expression with AND and OR in SparkR?如何在 SparkR 中使用 AND 和 OR 编写逻辑列表达式?
【发布时间】:2017-12-09 05:09:08
【问题描述】:

我需要根据其他几列的一些逻辑标准将列添加到 SparkR(spark 版本 2.1.1)数据集。但明显的解决方案(使用 && 或 ||)不起作用,我收到“invalid 'x' type in 'x && y'”错误。比如使用内置的mtcars数据集:

> dcars = as.DataFrame(mtcars)
> dcars$cool_enough <- dcars$cyl >= 6 && dcars$hp >= 180
Error in dcars$cyl >= 6 && dcars$hp >= 180 : invalid 'x' type in 'x && y'

我该怎么做?

【问题讨论】:

    标签: r apache-spark apache-spark-sql spark-dataframe sparkr


    【解决方案1】:

    为什么是&amp;&amp;?简单的&amp; 工作正常:

    sparkR.version()
    # "2.1.1"
    
    dcars$cool_enough <- dcars$cyl >= 6 & dcars$hp >= 170 # changed 180 to 170 for demonstration purposes
    head(dcars)
    

    结果:

       mpg cyl disp  hp drat    wt  qsec vs am gear carb cool_enough
    1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4       FALSE
    2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4       FALSE
    3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1       FALSE
    4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1       FALSE
    5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2        TRUE
    6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1       FALSE
    

    或者,这给出了相同的结果:

    dcars <- withColumn(dcars,"cool_enough", dcars$cyl >= 6 & dcars$hp >= 170)
    

    【讨论】:

    • 我确信我也尝试过 & 但它没有用.. 但现在它可以工作了,谢谢(我是 R 新手,并没有真正得到区别)。非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2013-03-17
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多