【问题标题】:How to use substring function in R when you have a vector?有向量时如何在 R 中使用子字符串函数?
【发布时间】:2017-01-07 14:30:12
【问题描述】:

我需要使用substring函数从数据框中按位置提取字符,如图所示:

这是我使用的代码:

substring(df$Text1,
          df$'Location of Different Letters',
          df$'Location of Different Letters')

substring 函数在数字为字符串格式的每一行中引入NAs。任何建议如何使它工作?由于c():,在“不同字母的位置”列上使用as.integer 不起作用

【问题讨论】:

  • Location of different letters 是什么类?
  • 我有字符和列表格式,上面的方法应用于字符列,当然不适用于列表列

标签: r string vector integer substring


【解决方案1】:

你有Location of different letters作为一个字符列,这会让事情变得有点难看,因为我们必须使用eval(parse(..))

## create a index list
cmd <- paste0("list(", toString(df$"Location of different letters"), ")")
# [1] "list(4, c(1,6,7,8), 3:6)"
ind <- eval(parse(text = cmd))
## split your strings
s <- strsplit(df$Text1, "")
## use `mapply`
set1 <- mapply("[", s, ind)

## now compare with `Text2` to get different letters
set2 <- strsplit(df$Text2, "")
mapply(function (a, b) paste0(setdiff(a, b), collapse = ""), set1, set2)
# [1] "d"    "FADX" "123" 

数据:

df <- data.frame(Text1 = c("abcd", "FxyznADX", "Don123"),
                 Text2 = c("abc", "xyzn", "Don"),
                 "Location of different letters" = c("4", "c(1,6,7,8)", "3:6"),
                 check.names = FALSE)

【讨论】:

    【解决方案2】:

    如果您的 Location of different letters 列中有值向量,则此方法有效。

    out <- sapply(c(1, 6, 7, 8), FUN = function(x) substring("FxyznADX", first = x, last = x))
    
    do.call(paste, args = list(as.list(out), collapse = ""))
    [1] "FADX"
    

    如果您有值的字符/因素,您可能需要求助于eval(parse(...))

    sapply(eval(parse(text = "c(1, 6, 7, 8)")), FUN = function(x) substring("FxyznADX", first = x, last = x))
    
    [1] "F" "A" "D" "X"
    

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2021-03-31
      • 2020-05-10
      • 1970-01-01
      • 2019-01-14
      • 2020-05-29
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多