嵌套循环以查找最近的注释



我有一个表,其中包含18个变量,这些变量包含对业务中工作流项目的注释(更新(。这些变量被命名为comment_0comment_17

每次添加新注释时,都会将其插入到每一行的最高空格中(即,如果之前有2条注释,则下一条注释会添加到comment_2列下(。

我需要创建一个新列,为每一行复制最新的注释。此列的内容已在下面">new_column"下的数据中进行了模拟。

数据:

df1 <- read.table(text = "comment_0   comment_1   comment_2   comment_3   comment_4   comment_5   new_column
NA  NA  NA  NA  NA  NA  NA
text0   text1   text2   text3   text4   text5   text5
NA  NA  NA  NA  NA  NA  NA
text0   NA  NA  NA  NA  NA  text0
NA  NA  NA  NA  NA  NA  NA
NA  NA  NA  NA  NA  NA  NA
text0   NA  NA  NA  NA  NA  text0
text0   text1   text2   NA  NA  NA  text2
text0   NA  NA  NA  NA  NA  text0
text0   NA  NA  NA  NA  NA  text0", header = TRUE, stringsAsFactors = FALSE)

反转数据帧,然后使用dplyr::coalize:获得第一个非NA值

library(dplyr)
coalesce(!!!df1[, 6:1])
# [1] NA      "text5" NA      "text0" NA      NA      "text0" "text2" "text0" "text0"
# test
identical(df1$new_column, coalesce(!!!df1[, 6:1]))
# [1] TRUE

不需要使用循环,我们可以使用max.colties.method = "last"来获得每行中最后一个非NA条目的列索引,使用cbind来创建行-列对,然后对数据帧进行子集设置。

df$new_column <- df[cbind(1:nrow(df), max.col(!is.na(df), ties.method = "last"))]
df
#   comment_0 comment_1 comment_2 comment_3 comment_4 comment_5 new_column
#1       <NA>      <NA>      <NA>      <NA>      <NA>      <NA>       <NA>
#2      text0     text1     text2     text3     text4     text5      text5
#3       <NA>      <NA>      <NA>      <NA>      <NA>      <NA>       <NA>
#4      text0      <NA>      <NA>      <NA>      <NA>      <NA>      text0
#5       <NA>      <NA>      <NA>      <NA>      <NA>      <NA>       <NA>
#6       <NA>      <NA>      <NA>      <NA>      <NA>      <NA>       <NA>
#7      text0      <NA>      <NA>      <NA>      <NA>      <NA>      text0
#8      text0     text1     text2      <NA>      <NA>      <NA>      text2
#9      text0      <NA>      <NA>      <NA>      <NA>      <NA>      text0
#10     text0      <NA>      <NA>      <NA>      <NA>      <NA>      text0

我们还可以按行使用apply(当可以使用max.col时不建议使用((使用MARGIN = 1(,并获得每行中的最后一个非NA值。

df$new_column <- apply(df, 1, function(x)  x[which.max(cumsum(!is.na(x)))])

最新更新