【问题标题】:search for string in column names and retrieve corresponding value for each row在列名中搜索字符串并检索每一行的相应值
【发布时间】:2018-10-15 01:02:23
【问题描述】:

我有一个这样的 df:

id <- c("defoo","ghfoo","abfoo")
abc <- c(.3,.1,.4)
ghi <- c(.4,.2,.2)
abc_dif <- c(.4,.3,.8)
def_dif <- c(.5,.7,.6)
ghi_dif <- c(.2,.1,.9)
df <- data.frame(id,abc,ghi,abc_dif,def_dif,ghi_dif)

我想查找名称包含 id 行中值的前两个字符并且还包含“dif”的列,并为每一行创建一个包含这些列中相应值的新列。

在此示例数据中,新列将是

df$result <- c(.5,.1,.8)

我的无数次尝试都涉及到各种版本的 sapply 和 apply,例如以下尝试简单地获取列索引:

df$result <- apply(substr(df[,which(colnames(df)=="id")],1,2),1,function(x) grep(x,colnames(df[which(grepl("dif",colnames(df),fixed=TRUE))]),fixed = TRUE))

这给出了错误:

"Error in apply(substr(df[, which(colnames(df) == "id")], 1, 2), 1, function(x) grep(x,  : 
  dim(X) must have a positive length"

最好的方法是什么?

【问题讨论】:

    标签: r string dataframe subset


    【解决方案1】:

    您可以遍历df$id,然后为每一个选择df 中的相关单元格:

    df$result <- sapply(df$id, function(x) df[df$id == x,
                                              grepl(paste0(substring(x,1,2),".*dif"), names(df))])
    
    df$result
    #[1] 0.5 0.1 0.8
    

    【讨论】:

      【解决方案2】:

      你可以试试tidyverse

      library(tidyverse)
      
      df %>% 
        gather(k,v, -id:-ghi) %>% 
        filter(str_sub(id,1,2) == str_sub(k,1,2)) %>% 
        select(1,result=v) %>% 
        left_join(df, .)
           id abc ghi abc_dif def_dif ghi_dif result
      1 defoo 0.3 0.4     0.4     0.5     0.2 0.5
      2 ghfoo 0.1 0.2     0.3     0.7     0.1 0.1
      3 abfoo 0.4 0.2     0.8     0.6     0.9 0.8
      

      【讨论】:

        【解决方案3】:

        我们可以创建一个row/column 索引来获取值

        df$result <- df[4:6][cbind(1:nrow(df), match( substr(df$id, 1, 2),
                        substr(names(df)[4:6], 1, 2)))]
        
        df$result
        #[1] 0.5 0.1 0.8
        

        【讨论】:

          猜你喜欢
          • 2012-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          • 1970-01-01
          • 2021-07-11
          • 2021-10-06
          • 1970-01-01
          相关资源
          最近更新 更多