For循环返回NA' s:仅返回ifelse语句的第一个匹配项

时间:2018-01-23 14:25:21

标签: r loops if-statement

如何让我的for循环只返回ifelse语句的第一个匹配?

这是我的数据框:

df <- structure(
  list(
x0 = c("0", "0", "0", "0", "0", "0", "0", "0",
       "0", "0"),
x1 = c("0", "0", "0", "0", "0", "0", "0", "0", "0",
       "0"),
x2 = c("0", "0", "0", "0", "0", "0", "0", "0", "0", "0"),
x3 = c("0", "0", "0", "0", "1", "0", "0", "0", "0", "0"),
x4 = c("0", "0", "0", "0", NA, "0", "0", "0", NA, "0"),
x5 = c("0",
       "0", "0", "0", NA, "0", "0", "0", NA, "0"),
x6 = c("0", "0",
       "0", "0", NA, "0", "0", "0", NA, "0"),
x7 = c("0", "0", "0",
       "0", NA, "0", "0", "0", NA, "0"),
x8 = c("0", "0", "0", "0",
       NA, "0", "0", "0", NA, "0"),
x9 = c("0", "0", "0", "0", NA,
       "0", "0", "0", NA, "1"),
x10 = c("0", "0", "0", "0", NA,
        "0", "0", "1", NA, "1"),
x11 = c("0", "0", "0", "0", NA,
        "0", "0", "1", NA, "2"),
x12 = c("0", "0", "0", "0", NA,
        "0", "0", "0", NA, "2"),
x13 = c("0", "0", "0", "0", NA,
        "0", "0", "1", NA, "3"),
x14 = c(NA, NA, "0", "0", NA, NA,
        NA, "2", NA, NA),
x15 = c(
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_,
  NA_character_
)
  ),
  .Names = c(
"x0",
"x1",
"x2",
"x3",
"x4",
"x5",
"x6",
"x7",
"x8",
"x9",
"x10",
"x11",
"x12",
"x13",
"x14",
"x15"
  ),
  row.names = c(NA, 10L),
  class = "data.frame"
)

以下是我希望实现的预期输出:

df$expectedoutput <- c(NA, NA, NA, NA, NA, NA, NA, 'x14', NA, 'x11')

这是我尝试获得所述输出:

df$newvar <- NA
for (i in 1:16) {
   df$newvar <- ifelse(df[,i] == "2" & is.na(df$newvar), 
                                  colnames(df[i]), NA)
}

我认为我的问题是我创建的for循环继续到最后并覆盖发生的第一个匹配,例如对于第10行,而不是完成df[10,12]的列名称,循环继续df[10,16],因此返回NA但是,我可能错了,也许这不是我的问题

1 个答案:

答案 0 :(得分:2)

首先,使用apply获取前2的列索引。
接下来,获取与该索引相对应的名称

first2 <- apply(df, MARGIN = 1, FUN = function(x) head(which(x == 2), 1))
df$newvar <- 
  vapply(first2, 
         FUN = function(x) if (length(x)) names(df)[x] else NA_character_, 
         character(1))

for循环等效项

df$newvar <- NA
for (i in seq_len(nrow(df))){
  first2 <- head(which(df[i, ] == 2), 1)
  df$newvar[i] <- if (length(first2)) names(df)[first2] else NA
}