简体   繁体   中英

R combining a df with a factor

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM