简体   繁体   English

R 结合一个 df 和一个因子

[英]R combining a df with a factor

I am pretty new to R and am trying to combine a df with a factor.我对 R 很陌生,正在尝试将 df 与因子结合起来。

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.我的 df 是一个 300 x 2 的数据帧,该因子是通过对 300 行进行采样并将它们分配给 1,2,3 来创建的。 I would like to know how to combine my factor to the df.我想知道如何将我的因素与 df 结合起来。 Basically, I want the factor variable shown as a column of my df.基本上,我希望因子变量显示为我的 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.我试过merge(db, factors)但它没有用。 I also tried to turn the factors variable into a df, but still couldn't get it to work.我还尝试将因子变量转换为 df,但仍然无法使其正常工作。

Your df is a matrix, not a data frame.你的df是一个矩阵,而不是一个数据框。 Make it a data frame, then you can add factors as a column easily:将其设为数据框,然后您可以轻松地将factors添加为一列:

df <- rmvnorm(300, mean = c(3, 3), sigma = cv)
class(df) # "matrix"

df <- data.frame(df)
class(df) # "data.frame"

df$factors <- factors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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