I have a dataframe with one column and some rows which I want to transform into a vector. The name of the column should be the name of the vector as well. Usually, I create another object doing this:
new_object <- as.vector(df$variable_name)
new_object
Is there a way to keep the variable name as the name of the vector?
(I am asking as I try to build this in a function and need it therefore)
Thank you!
CodePudding user response:
You can use list2env
-
df <- data.frame(a = 1:5)
list2env(df, .GlobalEnv)
a
#[1] 1 2 3 4 5
CodePudding user response:
sub <-c("A","A","A","A","B","B","B","B","C","C","C","C")
n<-c(0,1,1,1,0,1,0,1,0,1,0,1)
df <- data.frame(sub, n)
n <- df$n
[1] 0 1 1 1 0 1 0 1 0 1 0 1
You should be able to just simply call the variable name to get the vector.
CodePudding user response:
df <- data.frame(x = c(1, 2, 3))
assign(names(df), df[,1])
x
# [1] 1 2 3
CodePudding user response:
We could use attach
attach(df)
-output
> a
[1] 1 2 3 4 5
data
df <- data.frame(a = 1:5)