可能这里最简单的解决方案是使用 SQL:
# Because it is hard to live without pipes
library(magrittr)
# Create sqlContext
sqlContext <- sparkRSQL.init(sc)
sqlContext <- SQLContext(sc)
# Register table
registerTempTable(df, 'df')
# Query
sql(sqlContext, "SELECT *, IF(C0 = 0, 'yes', 'no') AS C0 FROM df") %>% showDF()
不幸的是,它创建了一个重复的名称,因此它可能首先重命名现有的名称:
df <- df %>% withColumnRenamed(existingCol = 'C0', newCol = 'CO_old')
registerTempTable(df, 'df')
sql(sqlContext, "SELECT *, IF(C0_old = 0, 'yes', 'no') AS C0 FROM df")
或简单地替换*
为您需要的列列表。
也可以使用when
/ otherwise
:
df %>% select(when(df$C) == 0, 'yes') %>% otherwise('no'))