代码之家  ›  专栏  ›  技术社区  ›  MAPK

如果大于R中的特定长度,如何删除列值中的最后一个字符?

r
  •  1
  • MAPK  · 技术社区  · 7 年前

    deseq.res

    deseq.res<-structure(list(Gene = c("SS1G_0300902", "SS1G_024991", "SS1G_09248", 
    "SS1G_09768"), sampleA = c("Healthy", "Healthy", "Healthy", "Healthy"
    ), sampleB = c("Infected", "Infected", "Infected", "Infected"
    )), .Names = c("Gene", "sampleA", "sampleB"), row.names = c(NA, 
    4L), class = "data.frame")
    

    我想要的结果是:

            Gene sampleA  sampleB
    SS1G_03009 Healthy Infected
    SS1G_02499 Healthy Infected
    SS1G_09248 Healthy Infected
    SS1G_09768 Healthy Infected
    

    我试过的代码:

    这就是我遇到的问题,然后我可以简单地使用gsub或substring。我可以用更精细的方法来做,但我想用函数来做这件事。

    check.len<- function(x){if (length(deseq.res$Gene[x])>10) return (x)}
    check.len(deseq.res$Gene)
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   akrun    7 年前

    我们可以使用 substr

    deseq.res$Gene <- substr(deseq.res$Gene, 1, 10)
    

    根据OP的功能,它是 nchar 而不是 length

    check.len <- function(x, n) ifelse(nchar(x) > n, substr(x, 1, n) , x)
    check.len(deseq.res$Gene, n = 10)
    
        2
  •  0
  •   DevGin    7 年前

    您可以使用库(dplyr)和变体:

    library(dplyr)
    deseq.res <- deseq.res %>% mutate(Gene = substr(Gene,1,10))