使用公共行动态分割数据帧

时间:2017-03-01 03:34:24

标签: r dataframe

我有一个名为data的数据框:

http://myherokuapp.herokuapp.com

我希望根据Select.Actions的值设置单独的数据框。

**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

然后我想将数据与d的输入匹配。因为d是动态的并且它会随着时间的推移而改变所以我写了一个循环来将数据帧拆分到不同的数据帧:

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

然后我收到以下警告信息。

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

你可以用逻辑来告诉我吗?

,输出为NULL。

1 个答案:

答案 0 :(得分:1)

您要在z[i]<-subset(data, ...中分配多个行和列,您可以使用rbind。我建议不要使用Hadely here解释的subset。如果以下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.

但是,我不会首先根据您的需要使用循环。