【问题标题】:Matching row entries with column names in R将行条目与 R 中的列名匹配
【发布时间】:2013-04-03 14:24:48
【问题描述】:

我是 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”和opt$week==price$week 中的列名匹配,我现在想提取“data.frame price”中的数字。

下一步是将选定的数字添加到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 技能有限。

任何帮助将不胜感激!

唐纳德

【问题讨论】:

    标签: r


    【解决方案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 的行名指定为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"
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多