如何在 R 中存储与原始数据相比被替换的日志?

How can I store logs that are replaced compared with original data in R?

我已经询问并得到了关于这个话题的

但是,另外,我想检查新列中替换了哪些数据。我刚试过下面,

df$check <- str_match_all(df, "\d{11}") %% unlist

但是,它不起作用。最终,我想得到下面的数据集。

              original               edited       check
1        010-1234-5678        010-1234-5678            
2   John 010-8888-8888   John 010-8888-8888            
3 Phone: 010-1111-2222 Phone: 010-1111-2222            
4  Peter 018.1111.3333  Peter 018.1111.3333            
5 Year(2007,2019,2020) Year(2007,2019,2020)            
6    Alice 01077776666  Alice 010-9999-9999 01077776666

这是我的代码。

x = c("010-1234-5678",
      "John 010-8888-8888",
      "Phone: 010-1111-2222",
      "Peter 018.1111.3333",
      "Year(2007,2019,2020)",
      "Alice 01077776666")

df = data.frame(
  original = x
)

df$edited <- gsub("\d{11}", "010-9999-9999", df$original)

df$check <- c("","","","","","01077776666") # I want to know the way here.

谢谢。

在使用 `==`ifelse 中,您可以测试列是否匹配,如果不匹配,则使用 gsub 匹配第一个数字并获取它和字符串的其余部分出自 "original".

transform(df, check=ifelse(!do.call(`==`, df[c("original", "edited")]), 
                           gsub('(\D*)(\d.*)', '\2', original),
                           NA))
#               original               edited       check
# 1        010-1234-5678        010-1234-5678        <NA>
# 2   John 010-8888-8888   John 010-8888-8888        <NA>
# 3 Phone: 010-1111-2222 Phone: 010-1111-2222        <NA>
# 4  Peter 018.1111.3333  Peter 018.1111.3333        <NA>
# 5 Year(2007,2019,2020) Year(2007,2019,2020)        <NA>
# 6    Alice 01077776666  Alice 010-9999-9999 01077776666