2017-03-01 90 views
0

我有一個數據幀被稱爲數據:分割數據幀動態

**Select.Actions**  **Current.State** **Next.State** 
Hire new staff   Out of Benchmark Withinbenchmark 
Hire new staff   Out of Benchmark Withinbenchmark 
Discuss with Customer Withinbenchmark Withinbenchmark 
Discuss with Customer Withinbenchmark Withinbenchmark 
Discuss with Customer Out of Benchmark Out of Benchmark 
Fire new staff   Out of Benchmark Withinbenchmark 
Discuss with Customer Withinbenchmark Withinbenchmark 
Discuss with Customer Out of Benchmark Withinbenchmark 
Fire new staff   Out of Benchmark Withinbenchmar 

我想基於Select.Actions的值,以具有單獨的數據幀。

#select First Column of dataframe 
d<-data[1] 

然後我想匹配數據與d的輸入。因爲d是動態的,它會隨着時間而改變,所以我寫了一個循環的數據幀拆分到不同的數據幀:

split<-for(i in 1:length(d)){ 
z[i]<-subset(data, data[,"Select.Actions"] %in% d[i],select=c(Current.State,Next.State))} 

然後我得到了下面的警告消息。

Warning message: 
In `[<-.data.frame`(`*tmp*`, i, value = list(Current.State = integer(0), : 
    provided 2 variables to replace 1 variables 

請問您能在邏輯方面給我建議嗎?

並且輸出爲NULL。

+0

什麼阻止你使用'?split'函數? – discipulus

+0

如果我使用拆分功能,我也必須使用循環,因爲正如我所提到的,Select.Actions的輸入是動態的,它會由用戶改變。所以我需要編寫一個動態代碼來分割數據框。 – user

+0

'd <-data [1]'不會選擇任何列,順便說一句。你需要'數據[,1]'。我沒有完全明白你在做什麼。可以採用什麼值? – Jean

回答

1

您正在分配z[i]<-subset(data, ...中的多個行和列,您可以使用rbind。我建議不要使用subset,如Hadely here所解釋的那樣。請讓我知道dplyr解決方案是否適合您。

library(dplyr) 
data <- read.table(text = 'Select.Actions,Current.State,Next.State 
Hire new staff,Out of Benchmark,Withinbenchmark 
Hire new staff,Out of Benchmark,Withinbenchmark 
Discuss with Customer,Withinbenchmark,Withinbenchmark 
Discuss with Customer,Withinbenchmark,Withinbenchmark 
Discuss with Customer,Out of Benchmark,Out of Benchmark 
Fire new staff,Out of Benchmark,Withinbenchmark 
Discuss with Customer,Withinbenchmark,Withinbenchmark 
Discuss with Customer,Out of Benchmark,Withinbenchmark 
Fire new staff, Out of Benchmark,Withinbenchmar', 
        header = TRUE, sep =",", stringsAsFactors = FALSE) 



z <- NULL 
for(i in 1:nrow(data)) 
{ 
    interm_data <- data %>% filter(Select.Actions == data[i,1]) %>% select(Current.State, Next.State) 
    if(is.null(z)) 
    { 
    z<- interm_data 
    }else{ 
    z<- rbind(z,interm_data) 
    } 
    print(data[i,1]) 
    print(interm_data) 

} 

** **更新

基於用戶的評論。

z <- list() 
trim <- function (x) gsub("^\\s+|\\s+$", "", x) 
for(i in unique(data$Select.Actions)) 
{ 
    z[[trim(i)]] <- data %>% filter(Select.Actions == i) %>% select(Current.State, Next.State) 
} 
list2env(z ,.GlobalEnv) 
# Now you will have 3 data sets `Hire new staff`, `Fire new staff` and `Discuss with customer` in your workspace. 

但是,我不會首先使用循環來滿足您的需求。

+0

謝謝,但輸出中有重複,在這種情況下,我想只有3個數據[1]聘請新員工,[2]與客戶討論[3]消防新員工,我想根據不同的行動過濾數據幀,並將每個數據幀保存爲一個新數據幀 – user

+0

而不是nrow(數據)我用d <-unique(data [1])來解決複製問題,但我不能單獨保存每個數據幀。 – user

+0

新的更新代碼如何去除重複並分別創建3個數據幀? – discipulus