0

我是 R 新手,正在尝试将几个数据集合并为一个。我的数据结构如下:

opt <- data.frame( name=c("opt1", "opt2","opt3"), week=c(1,1,1,2,2,3), price=c(0))

price <- data.frame( week=c(1,2,3), opt1=c(3, 4,3.15), opt2=c(4.2, 3.5, 5), opt3=c(3,2,6))

opt$name如果行中的条目与“data.frame price”中的列名匹配,我现在想提取“data.frame price”中的数字,并且opt$week==price$week

下一步是将选定的数字添加到opt$price列中。要创建一个如下所示的新 data.frame:

optcomp <- data.frame( name=c("opt1", "opt2","opt3"), week=c(1,1,1,2,2,3), price=c(3.00,4.2,3,4.00,3.5,6))

我试图构建一些循环,但我的 R 技能有限。

任何帮助将不胜感激!

唐纳德

4

1 回答 1

1

初始合并,以匹配week列:

x <- merge(opt,price)

x
##   week name price opt1 opt2 opt3
## 1    1 opt1     0 3.00  4.2    3
## 2    1 opt2     0 3.00  4.2    3
## 3    1 opt3     0 3.00  4.2    3
## 4    2 opt1     0 4.00  3.5    2
## 5    2 opt2     0 4.00  3.5    2
## 6    3 opt3     0 3.15  5.0    6

您想要的值:

sapply(seq(nrow(x)), function(i) x[i,as.character(x$name[i])])
[1] 3.0 4.2 3.0 4.0 3.5 6.0

x指定as的行名称character允许按名称进行矩阵索引(并返回character

rownames(x) <- as.character(rownames(x))
x.ind <- matrix(c(rownames(x), as.character(x$name)),,2)
x[x.ind]
## [1] "3.00" "4.2"  "3"    "4.00" "3.5"  "6"
于 2013-04-03T14:35:52.900 回答