2016-03-07 319 views
0

在sparkR中我有一個DataFrame data。 當我鍵入head(data)我們得到如下的輸出刪除DataFrame中的列名稱

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") 
+0

我想你已經讀了錯誤的數據幀。您想要刪除數據框的列名稱並將行1作爲新的列名稱,對嗎? –

+0

是的,這是正確的。 –

+0

然後你不能這樣做:'colnames(data)= data [1,]'和'data = data [-1,]'? – Konrad

回答

3

SparkR將頭部放入第一行,並給DataFrame一個新頭,因爲頭部選項的默認值爲「false」。將header選項設置爲header =「true」,然後你就不必處理這個問題。

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

這是唯一正確的答案。 –

2

數據嘗試

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以糾正行號。

該操作後,可以選擇喜歡

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

在鹼R對應於特定條件的行,該函數filter()在OP建議是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")) 
+0

你爲什麼'unlist'獲取姓氏?不會'colnames(data)< - data [1,]'做到這一點嗎? – Sotos

+1

@Sotos你嘗試過嗎?讀取文件的默認設置是'stringsAsFactors = TRUE',這就是爲什麼你的建議不起作用,至少在我的電腦上不行。當我使用你的代碼時,名字是「6」,「6」,「5」,「6」,這對應於第一行中條目的級別號碼(在列內)。 – RHertel

+1

啊......好吧,我明白了。它需要成爲一個角色才能在沒有'unlist'的情況下工作。歡呼聲 – Sotos

0

試試這個

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

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

我根本就沒有因爲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函數,因爲我想。

相關問題