首页 > 解决方案 > 数据框创建观察而不是变量

问题描述

我在 R 中有一个奇怪的问题。我想创建一个包含两个变量的数据框,但它只给了我一个包含大量观察结果的变量。

在下面的示例中,第一个数据框是正确的并给出了三​​个变量,但第二个只有一个。为什么会这样,我该如何改变它?

谢谢

t1 <- c(1:5)
t2 <- c(1:5)
t3 <- c(1:5)
test.data <- data.frame(t1, t2, t3)
str(plot.data) 
#Three variables are in the data frame.


one <- c(1:5)
two <- c(1:15)
three <- c(1:10)

plot.data <- data.frame("id"=rbind(
c(
  rep(1,times = length(one)),
  rep(2,times = length(two)),
  rep(3,times = length(three)))), "obs"=
  rbind(c(one, two, three))
)
str(plot.data)
#There is only one variable in the data frame, but there should be two (id and obs)!

标签: r

解决方案


使用rbind,您将获得一个数据结构,该结构需要您调用xy以不同的方式获取值:

> x <- rbind(
  c(
    rep(1,times = length(one)),
    rep(2,times = length(two)),
    rep(3,times = length(three))))
> y <- (rbind(c(one, two, three)))
> str(x)
 num [1, 1:30] 1 1 1 1 1 2 2 2 2 2 ...
> str(y)
 int [1, 1:30] 1 2 3 4 5 1 2 3 4 5 ...

要仅获取值(为了进行对比,只需键入x并比较):

> x[,]
 [1] 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
> y[,]
 [1]  1  2  3  4  5  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15  1  2  3  4  5  6  7  8  9 10

所以创建这样的数据框:

> df <- data.frame(x=x[,],y=y[,])
> df
   x  y
1  1  1
2  1  2
3  1  3
4  1  4
5  1  5
6  2  1
7  2  2

推荐阅读