【问题标题】:How to get the value from a column of a dataframe with the key of another column in R?如何使用 R 中另一列的键从数据框的列中获取值?
【发布时间】:2021-01-24 01:53:09
【问题描述】:

我有一个包含两列 A (char) 和 B (num) 的数据框。我想找到 B 的对应值,对于 A 的值。

例如,我有以下数据,我想从 B 列中找到“b”的值并将其分配给某个变量 val。我们不知道 a,b,c,d 的顺序,所以我们想使用给定的字符。

enter image description here

所以 val = 5

【问题讨论】:

    标签: r dataframe indexing


    【解决方案1】:

    我们可以创建一个包含“A”列的逻辑向量,将“B”值作为子集并将其分配(<-)给对象“val”

    df<-data.frame("A"=c('a', 'b', 'c', 'd'), "B"=c(3, 5, 8, 2))
    
    val <- with(df, B[A=='b'])
    

    【讨论】:

      【解决方案2】:

      你可以使用match

      val <- df$B[match('b', df$A)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 2020-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        相关资源
        最近更新 更多