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)!
解决方案
使用rbind
,您将获得一个数据结构,该结构需要您调用x
并y
以不同的方式获取值:
> 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
推荐阅读
- javascript - 如果使用javascript的两个数组的empId相同,如何删除重复的empId记录行
- javascript - 如何从具有种子的数组中随机选择 n 个项目,当在 JavaScript 中给出固定种子时,可以让随机化固定?
- javascript - 来自 MongoDB 的 id 等于 React 应用程序中的未定义
- asp.net-core - 如何从 Postman/WebSocket King 调用 SignalR Core 集线器方法
- java - 生产者和消费者使用带有嵌入式主题的 kafka 和 apache camel
- python - 如何更新时间?
- python - 当它比较的数据是 None 类型时,DataFrame.ne 返回 false
- powerbi - 如何使用选定的值来计算并将更改仅应用于选定的组?
- imagemagick - 用imagemagick随机填充
- python - 如何使用 matplotlib/seabornn 将边缘线添加到图例上的标记