2

我有一个 SparkR 数据框,其中所有列都是整数。我想用字符串替换一列。

因此,如果该列包含 0、1、1、0,我想将其设为“否”、“是”、“是”、“否”。

我试过了

df$C0 <- ifelse(df$C0 == 0, "no", "yes)

但这只是给了我

 Error in as.logical(from) : 
   cannot coerce type 'S4' to vector of type 'logical'

我将如何进行此更新?

PS我基于上面的尝试这个事实:

df$C0 <- df$C0 + 1
4

1 回答 1

3

可能这里最简单的解决方案是使用 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'))
于 2015-06-29T20:27:05.557 回答