在数据框的新列中打印匹配的位置

时间:2018-01-11 16:34:57

标签: r dataframe match

我想要做的是搜索一组列并返回一个新列 1.列中的字符串以及它来自的列的名称

df <- structure(list(ID = c("A1.1234567_10", "A1.1234567_20"), 
                 var1 = c("NORMAL", "NORMAL"), 
                 var2 = c("NORMAL", "SUSPECTED"), 
                 var3 = c("NORMAL", "NORMAL"), 
                 var4 = c("NORMAL", "NORMAL"), 
                 var5 = c("NORMAL", "NORMAL"), 
                 var6 = c("NORMAL", "NORMAL"), 
                 var7 = c("NORMAL", "ABNORMAL"), 
                 var8 = c("NORMAL", "NORMAL")), 
            .Names = c("ID", "var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8"), 
            class = "data.frame", row.names = c(NA, -2L))

           ID   var1   var2   var3   var4   var5   var6     var7   var8
A1.1234567_10  NORMAL NORMAL NORMAL NORMAL NORMAL NORMAL   NORMAL NORMAL
A1.1234567_20 NORMAL SUSPECTED NORMAL NORMAL NORMAL NORMAL ABNORMAL NORMAL

我想最终看起来像这样

           ID   var1   var2   var3   var4   var5   var6     var7   var8  abnormal_summary
A1.1234567_10 NORMAL NORMAL    NORMAL NORMAL NORMAL NORMAL   NORMAL NORMAL NA
A1.1234567_20 NORMAL SUSPECTED NORMAL NORMAL NORMAL NORMAL ABNORMAL NORMAL suspected_var2 ABNORMAL_var7 

我知道我可以自己编制索引,但是最终要查看它的人需要在每一行中对其进行可视化。

1 个答案:

答案 0 :(得分:1)

apply函数将成为遍历每一行的主力。在每一行上使用自定义函数来编译“坏”的字符串向量&#39;值及其对应的列名索引。在连接行上找到的所有错误值列组合之前,合并错误值和列名称。最后,该行应作为可添加到原始数据帧的向量返回。

#This example uses the dataframe, `df` you defined in your question. 
#
# this function works on one row at a time and can accept one or more
# accepted values as a character vector.  
library(magrittr)

build_nonnorm_str <- function(row, col_names, norm_value) {
  # get the index of any bad values, excluding the column named "ID"
  bad_col_indx <- which(!row %in% norm_value &
                    !names(row) == "ID")

  # appropriately assign NA to rows with no bad values,
  # otherwise put together the string to be appended to
  # the new dataframe
  if (length(bad_col_indx > 0)) {
    abnorm_str <- paste0(row[bad_col_indx], 
                         "_",
                         col_names[bad_col_indx], 
                         sep = " ") %>%
      paste0(collapse = "") %>%
      trimws()
  } else {
    abnorm_str <- NA
  }

  return(abnorm_str)
}

# Use the apply function to send the function one rows worth of data
# and append it to the new column
df$abnormal_summary <- apply(df,
                             1,
                             build_nonnorm_str,
                             col_names = names(df),
                             norm_value = "NORMAL")

使用which语句中的逻辑来修改是否要排除所有不是&#34; NORMAL&#34;或者只包括那些&#34; ABNORMAL&#34;或者&#34;被怀疑&#34;。