数据框创建观察值而不是变量

时间:2018-07-01 13:48:49

标签: r

我在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)!

1 个答案:

答案 0 :(得分:0)

使用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
相关问题