Reputation: 13
I am pretty new to R and am trying to combine a df with a factor.
My df is a dataframe of 300 by 2, and the factor is created from sampling the 300 rows and assigning them to 1,2,3. I would like to know how to combine my factor to the df. Basically, I want the factor variable shown as a column of my df.
library(mvtnorm)
cv <- matrix(c(1, 0, 0, 1), ncol = 2)
df <- rmvnorm(300, mean = c(3, 3), sigma = cv)
factors <- factor(sample(c(1, 2, 3), 300, replace = TRUE))
I tried merge(db, factors)
but it did not work. I also tried to turn the factors variable into a df, but still couldn't get it to work.
Upvotes: 0
Views: 46
Reputation: 21264
Your df
is a matrix, not a data frame. Make it a data frame, then you can add factors
as a column easily:
df <- rmvnorm(300, mean = c(3, 3), sigma = cv)
class(df) # "matrix"
df <- data.frame(df)
class(df) # "data.frame"
df$factors <- factors
Upvotes: 1