分割数据帧动态
我有一个数据帧被称为数据:分割数据帧动态
**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。
您正在分配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.
但是,我不会首先使用循环来满足您的需求。
谢谢,但输出中有重复,在这种情况下,我想只有3个数据[1]聘请新员工,[2]与客户讨论[3]消防新员工,我想根据不同的行动过滤数据帧,并将每个数据帧保存为一个新数据帧 – user
而不是nrow(数据)我用d user
新的更新代码如何去除重复并分别创建3个数据帧? – discipulus
什么阻止你使用'?split'函数? – discipulus
如果我使用拆分功能,我也必须使用循环,因为正如我所提到的,Select.Actions的输入是动态的,它会由用户改变。所以我需要编写一个动态代码来分割数据框。 – user
'd Jean