删除 DataFrame 中的列名

Remove column names in a DataFrame

在 sparkR 中我有一个 DataFrame data。 当我输入 head(data) 时,我们得到这个输出

  C0      C1               C2         C3
1 id user_id foreign_model_id machine_id 
2  1   3145                4         12 
3  2   4079                1          8 
4  3   1174                7          1    
5  4   2386                9          9    
6  5   5524                1          7

我想删除 C0,C1,C2,C3 因为他们稍后会给我一个问题。例如,当我使用 filter 函数时:

filter(data,data$machine_id==1)

因此不能 运行。


我看过这样的资料

data <- read.df(sqlContext, "/home/ole/.../data", "com.databricks.spark.csv")

尝试

colnames(data) <- unlist(data[1,])
data <- data[-1,]
> data
#  id user_id foreign_model_id machine_id
#2  1    3145                4         12
#3  2    4079                1          8
#4  3    1174                7          1
#5  4    2386                9          9
#6  5    5524                1          7

如果您愿意,可以添加 rownames(data) <- NULL 以更正第一行删除后的行号。

进行此操作后,您可以 select 行对应于特定条件,例如

subset(data, data$machine_id==1)
#  id user_id foreign_model_id machine_id
#4  3    1174                7          1

在 base R 中,OP 中建议的函数 filter()stats 命名空间的一部分,通常保留用于时间序列的分析。

数据

data <- structure(list(C0 = structure(c(6L, 1L, 2L, 3L, 4L, 5L), 
      .Label = c("1", "2", "3", "4", "5", "id"), class = "factor"), 
       C1 = structure(c(6L, 3L, 4L, 1L, 2L, 5L), .Label = c("1174", "2386", 
      "3145", "4079", "5524", "user_id"), class = "factor"), 
      C2 = structure(c(5L, 2L, 1L, 3L, 4L, 1L), 
     .Label = c("1", "4", "7", "9", "foreign_model_id"), class = "factor"), 
      C3 = structure(c(6L, 2L, 4L, 1L, 5L, 3L), 
      .Label = c("1", "12", "7", "8", "9", "machine_id"), class = "factor")), 
     .Names = c("C0", "C1", "C2", "C3"), class = "data.frame", 
     row.names = c("1", "2", "3", "4", "5", "6"))

试试这个

names <- c()
for (i in seq(along = names(data))) {
   names <- c(names, toString(data[1,i]))
}

names(data) <- names
data <- data[-1,]

我根本无法使用答案,因为在 sparkR 中它不能 运行:object of type 'S4' is not subsettable。我以这种方式解决了问题,但是,我认为有更好的方法来解决它。

data <- withColumnRenamed(data, "C0","id")
data <- withColumnRenamed(data, "C1","user_id")
data <- withColumnRenamed(data, "C2","foreign_model_id")
data <- withColumnRenamed(data, "C3","machine_id")

现在我可以随心所欲地成功使用 filter 功能了。

SparkR 将 header 放入第一行并为 DataFrame 提供了一个新的 header,因为 header 选项的默认值为 "false"。将 header 选项设置为 header="true" 然后你就不必处理这个问题了。

data <- read.df(sqlContext, "/home/ole/.../data", "com.databricks.spark.csv", header="true")