-3

这是样本数据。

df1 <- data.frame(y = 1:5, x = c("s", "m", "l", "s", "m"))

df2 <- data.frame(y = 1:4, x = c("s", "l", "s", "l"))

我希望 df2 具有基于 df1$x 的三个级别。

我试过了

df2$x <- factor(df1$x)

然后我有

Error in `$<-.data.frame`(`*tmp*`, "x", value = c(3L, 2L, 1L, 3L, 2L)) : 
  replacement has 5 rows, data has 4

或者

levels(df2$x) <- factor(df1$x)

然后它改变了df2。

df2
  y x
1 1 m
2 2 s
3 3 m
4 4 s

我该怎么做?

4

2 回答 2

1

我不确定我是否正确理解了您的目标。

df1 <- data.frame(y = 1:5, x = factor(c("s", "m", "l", "s", "m")))
df2 <- data.frame(y = 1:4, x = factor(c("s", "l", "s", "l")))
df2$x
#[1] s l s l
#Levels: l s
levels(df2$x)<-unique(c(levels(df2$x),levels(df1$x)))
df2$x
#[1] s l s l
#Levels: l s m
于 2012-08-21T18:37:14.757 回答
0
df1 <- data.frame(y = 1:5, x = c("s", "m", "l", "s", "m"))

df2 <- data.frame(y = 1:4, x = factor(c("s", "l", "s", "l"), levels=levels(df1$x)))

 str(df2)
'data.frame':   4 obs. of  2 variables:
 $ y: int  1 2 3 4
 $ x: Factor w/ 3 levels "l","m","s": 3 1 3 1
于 2012-08-21T21:59:55.453 回答