Eric Hart
Eric Hart

Reputation: 21

How to make one data frame into multiple data frames

So I am trying to split one data frame into multiple. I currently have:

y <- data.frame(day=c('1','1','2','2'),amount=c(1,2,3,4))

for(i in 1:2){
    i <- as.character(i)
    for(j in 1:4){
        if (grep(i, y$day, value = TRUE) > 0){
            assign(paste0('df', i)) <- rbind(assign(paste0('df', i)),y[j])
        }
    }
}

It then gives me an error and warning saying:

Error in assign(paste0("df", i)) :

argument "value" is missing, with no default

In addition:

Warning message:

In if (grep(i, y$day, value = TRUE) > 0) { :the condition has length > 1 and only the first element will be used

I can't seem to find what value is supposed to be or where to put it.

Upvotes: 2

Views: 3517

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

I'd steer clear of assign unless you're setting up a new environment. If you're trying to split by day, then you can just use split

y <- data.frame(day=c('1','1','2','2'),amount=c(1,2,3,4))
split(y, y$day)
# $`1`
#   day amount
# 1   1      1
# 2   1      2
#
# $`2`
#   day amount
# 3   2      3
# 4   2      4

If you want them assigned to their own data frames in the global environment (not recommended), you can use list2env

s <- setNames(split(y, y$day), paste0("df", unique(y$day)))
list2env(s, globalenv())

Now you have data frames df1 and df2 in the global environment

df1
#   day amount
# 1   1      1
# 2   1      2
df2
#   day amount
# 3   2      3
# 4   2      4

Upvotes: 4

Related Questions