Home > Software design >  Split dataframe columns into vectors in R
Split dataframe columns into vectors in R

Time:11-19

I have a dataframe as such:

Number <- c(1,2,3)
Number2 <- c(10,12,14)
Letter <- c("A","B","C")
df <- data.frame(Number,Number2,Letter)

I would like to split the df into its respective three columns, each one becoming a vector with the respective column name. In essence, the output should look exactly like the original three input vectors in the above example.

I have tried the split function and also using for loop, but without success.

Any ideas? Thank you.

CodePudding user response:

We may use unclass as data.frame is a list with additional attributes. By unclassing, it removes the data.frame attribute

unclass(df)

Or another option is asplit with MARGIN specified as 2

asplit(df, 2)

NOTE: Both of them return a named list. If we intend to create new objects in the global env, use list2env (not recommended though)

CodePudding user response:

We can use c oras.list

> c(df)
$Number
[1] 1 2 3

$Number2
[1] 10 12 14

$Letter
[1] "A" "B" "C"

> as.list(df)
$Number
[1] 1 2 3

$Number2
[1] 10 12 14

$Letter
[1] "A" "B" "C"

CodePudding user response:

Assuming you are trying to create these as vectors if the global environment, use list2env:

df <- data.frame(Number = c(1, 2, 3), 
                 Number2 = c(10, 12, 14), 
                 Letter = c("A", "B", "C"))

list2env(df, .GlobalEnv)
## <environment: R_GlobalEnv>
ls()
## [1] "df"      "Letter"  "Number"  "Number2"

CodePudding user response:

list2env is clearly the easiest way, but if you want to do it with a for loop it can also be achieved.

The "tricky" part is to make a new vector based on the column names inside the for loop. If you just write

 names(df[i]) <- input 

a vector will not be created.

A workaround is to use paste to create a string with the new vector name and what should be in it, then use "eval(parse(text=)" to evaluate this expression.

Maybe not the most elegant solution, but seems to work.

for (i in colnames(df)){
  vector_name <- names(df[i])
  expression_to_be_evaluated <- paste(vector_name, "<- df[[i]]")
  eval(parse(text=expression_to_be_evaluated))
}

> Letter
[1] A B C
Levels: A B C
> Number
[1] 1 2 3
> Number2
[1] 10 12 14
  • Related