【问题标题】:Extract letters from a string at different positions in R从R中不同位置的字符串中提取字母
【发布时间】:2018-10-10 14:17:14
【问题描述】:

我有两列,我想从不同位置提取字母。目标是显示在 Col2 中使用了哪个字母来替换 Col1 中的字母。字母将根据位置列从 Col1 和 Col2 中提取。在 Position 列中,字母“E”表示将用于提取字母的位置。

这是我尝试使用substr 函数:

df <- data.frame ("Col1" = c("Stores","University","Street","Street Store"), 
       "Col2" = c("Ostues", "Unasersity", "Straeq","Straeq Stuwq"), 
       "Position" = c("EMMEMM","MMEEMMMMMM", "MMMEME","MMMEMEMMMEEE"), 
       "Desired Output" = c("S|O , r|u","i|a , v|s","e|a , t|q", "e|a , t|q , o|u , r|w , e|q"))


n <- which(strsplit(df$Position,"")[[1]]=="E")
#output for the first row:
# [1] 1  4

#then I used substr function:
substr(df$Col1, n, n)

#only the first character returned as below:
[1] "S"

#desired output for first row:
S|O , r|u

【问题讨论】:

  • 是的,前三列是输入的。我按照建议以可重现的格式添加了示例数据。
  • 您的 position 列似乎与示例第 1 行中的 Col1Col2 不一致。第 2 行和第 3 行显示实际更改的每个字母的 E,而不仅仅是颜色不同的字母。在第一行中,前四个字母已从 Col1 更改为 Col2Position 是否应该被视为给定的?还是在您的数据中计算得出?
  • @brittenb 给出了位置列。我输入数据时打错了。
  • 明白了。在这种情况下,@mr​​flick 有正确的解决方案。

标签: r substr


【解决方案1】:

首先我将创建一个辅助函数来从一个位置提取一个字符

subchr <- function(x, pos) {
  substring(x, pos, pos)
}

然后你就可以找到你要提取的所有位置了

extract_at <- lapply(strsplit(as.character(df$Position), ""), 
    function(x) which(x=="E"))

然后将它们放在一起以获得您想要的输出

mapply(function(e, a, b){
  paste(subchr(a, e), subchr(b,e), sep="|", collapse=" , ")
}, extract_at, as.character(df$Col1), as.character(df$Col2))
# [1] "S|O , r|u" "i|a , v|s" "e|a , t|q"

【讨论】:

  • 当我运行代码的最后一部分以获取输出时,我收到错误:点错误 [[1L]][[1L]] : 'closure' 类型的对象不是子集
  • 你的真实data.frame是否命名为df? (这也是 R 中的内置函数)。我猜可能有一个 df 实例你没有更改为你的真实变量名。
【解决方案2】:

也许是这样的:

df %>% mutate(x=str_replace_all(chartr("M",".",Position),"E","\\(\\.\\)"),
          output=paste0(str_replace(Col1,x,"\\1"),"|",str_replace(Col2,x,"\\1"),
                  " , ",str_replace(Col1,x,"\\2"),"|",str_replace(Col2,x,"\\2")))
#        Col1       Col2   Position Desired.Output              x    output
#1     Stores     Ostues     EMMEMM      S|O , r|u     (.)..(.).. S|O , r|u
#2 University Unasersity MMEEMMMMMM      i|a , v|s ..(.)(.)...... i|a , v|s
#3     Street     Straeq     MMMEME      e|a , t|q     ...(.).(.) e|a , t|q

数据:

    df <- data.frame ("Col1" = c("Stores","University","Street"), 
       "Col2" = c("Ostues", "Unasersity", "Straeq"), 
       "Position" = c("EMMEMM","MMEEMMMMMM", "MMMEME"), 
       "Desired Output" = c("S|O , r|u","i|a , v|s","e|a , t|q"))

【讨论】:

    猜你喜欢
    • 2015-09-03
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多