如何基于条件使用sum()填充列以匹配r

时间:2019-10-24 13:07:37

标签: r if-statement dplyr

我很难根据条件填写专栏。也许我的方法不正确。我不知道。我的条件如下:

  • 连续2个“ b”和1个“ a”,在“匹配”“ B”列中写入
  • 连续2个“ c”,在“ match”列“ C”中写入
  • 填写其他内容

到目前为止,我已经执行了以下操作,但是我发现这不太准确,因为我的新矢量不是从行而是整个列中创建的,并且仍然无法正常工作。

set.seed(123)
df_letters <- data.frame(basket1 = sample(letters[1:3], 5,  replace = TRUE, prob = c(0.85,0.10,0.5)),
                        basket2 = sample(letters[1:3], 5,  replace = TRUE, prob = c(0.10,0.85,0.5)),
                        basket3 = sample(letters[1:3], 5,  replace = TRUE, prob=c(0.5,0.10,0.85)),
                        stringsAsFactors = FALSE)


df_letters %>% mutate(match = ifelse(sum(as.character(as.vector(df_letters))  == "c")==2, "C", 
                                    ifelse((sum(as.character(as.vector(df_letters))  == "b")==2) & (sum(as.character(as.vector(df_letters))  == "a")==1) ,"B", NA  )))

我想要的输出是:

> df_letters
  basket1 basket2 basket3 match
1       a       b       b     B
2       c       b       c     C
3       a       c       a  <NA>
4       c       b       c     C
5       b       b       c  <NA>

非常感谢!

2 个答案:

答案 0 :(得分:1)

一个var arg = @"/c cd %ProgramFiles%\PostgreSQL\12\bin && SET PGPASSWORD=mypassword&& pg_restore.exe -U username -d dbname C:\file\to\dump\my.dump"; Process.Start("cmd.exe", arg); 选项可能是:

dplyr

答案 1 :(得分:1)

这是在base R中实现此目标的方法:

df_letters$match <- apply(df_letters, 1, function(x) {
  count <- as.list(table(x))
  ifelse(count$a == 1 && count$b == 2, "B", ifelse(count$c == 2, "C", NA_character_))
})

想法是将table对象转换为列表以按元素访问计数。

输出

      basket1 basket2 basket3 match
1       a       b       b     B
2       c       b       c     C
3       a       c       a  <NA>
4       c       b       c     C
5       b       b       c  <NA>