【问题标题】:fast looping and conditioning in R; insert new value in column based on the other columnR中的快速循环和调节;根据另一列在列中插入新值
【发布时间】:2020-07-07 16:21:53
【问题描述】:

我有大量数据,我想遍历数据并将结果插入到我命名为action2的新列中:

我的情况基于action 栏目:

if it contains "AA" OR "A1" then insert "As":
if it contains "BB" insert "Bs"
if it contains "AA" AND "C" then insert "AsC"
else insert the value in 'action' column 


df<- read.table(text="
user     action
1         AA
1         BB
1         ABCFF
1         A1B
2         AAB
2         BA1
2         AABC
3         M",header=T)

result df
user     action      action2
1         AA          As
1         BB          Bs
1         ABCFF       ABCFF
1         A1B         As
2         AAB         As    
2         BA1         As          
2         AABC        AsC
2         M           M

我怎样才能在 R 中做到这一点? (最好使用 dplyr 库)

【问题讨论】:

  • 如果需要更快的选项,你想要data.table
  • 有一个疑问,对于'AABC',它可以匹配到'AA'。你在寻找子字符串匹配还是固定匹配
  • @akrun 我正在寻找子字符串匹配,Tx

标签: r loops conditional-statements


【解决方案1】:

我认为case_when 会起作用,但正如@akrun 评论的那样,如果您需要速度,data.table 解决方案可能会更快。

df %>%
  mutate(action2 = case_when(
    grepl("AA.*C|C.*AA", action) ~ "AsC",
    grepl("A[A1]", action)       ~ "As",
    grepl("BB", action)          ~ "Bs",
    TRUE                         ~ action)
  )
#   user action action2
# 1    1     AA      As
# 2    1     BB      Bs
# 3    1  ABCFF   ABCFF
# 4    1    A1B      As
# 5    2    AAB      As
# 6    2    BA1      As
# 7    2   AABC     AsC
# 8    3      M       M

(为了使其按原样工作,我将您当前的 action 从一个因子转换为 character。由于您的数据只是玩具/样本,它可能不是您真实数据的一个因子。 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2021-09-13
    • 1970-01-01
    • 2016-06-21
    • 2022-01-23
    • 1970-01-01
    • 2015-04-11
    相关资源
    最近更新 更多