R - Unbind Dataframe

Viewed 144

I am trying to split a dataframe (df) into its constituent vectors

Example dataframe

v1 <- c(213, 225, 435)
v2 <- c(333, 888, 999)
v2 <- c(788, 666, 545)

df <- data.frame(v1, v2, v3)

Current syntax:

for (i in 1:3) {
  assign(paste('v', i, sep = '')) <- df$v[c(i)]
}

Desired output is just:

v1, v2, v3

Is there a way to do this using lapply? Is there a way to do this using a for loop?

2 Answers

Inside the assign, we specify the value argument and the x (which is object name as a string). Also v[c(i)] is incorrect as i is a numeric index and it is trying to subset v which doesn't exist. Inside it would be the same paste to create the column name along with [[ for dynamic subsetting

for (i in 1:3) {
  assign(paste('v', i, sep = ''), value = df[[paste0("v", i)]])
 }

Or instead of calling paste twice, can do

for(i in 1:3) {
    nm1 <- paste0("v", i)
    assign(nm1, value = df[[nm1]])
}

Or another option is

rm(list = paste0('v', 1:3)) # // remove the objects created in the env
list2env(df, .GlobalEnv)
v1
#[1] 213 225 435
v2
#[1] 788 666 545
v3
#[1] 788 666 545

Or can use attach as well. It is better not to create multiple objects in the global environment. Instead, it can be in a list or data.frame (if the objects are of equal length)

Use split.default to split every column into different dataframe.

res <- split.default(df, names(df))
res

#$v1
#   v1
#1 213
#2 225
#3 435

#$v2
#   v2
#1 333
#2 888
#3 999

#$v3
#   v3
#1 788
#2 666
#3 545

Use list2env if you need them as separate objects.

list2env(res, .GlobalEnv)
Related