有没有人能帮我算出每行单元格中一个字符的实例数?我有一个包含1000万个snps的文件,我想对其进行排序。
Direction
?????+-+-
?+-+-????
?-+-+??-+上面是我拥有的许多专栏中的一个例子。我想要做的是计算"?“的数量。字符,然后添加一个新列,并将该计数作为数值。
我完全是一个初学者,在这方面投入了很深的末端,所以任何帮助都将不胜感激。
谢谢。
发布于 2017-07-22 02:03:04
给你两个答案
a <- data.frame(direction = c("?????+-+-", "?+-+-????","?-+-+??-+"),
stringAsFactors = F)
a$return <- lengths(regmatches(a$direction, gregexpr("\\?", a$direction)))或根据评论
a$return <- nchar(gsub("[^?]", "", a$direction))两者都返回
'data.frame': 3 obs. of 2 variables:
$ direction: chr "?????+-+-" "?+-+-????" "?-+-+??-+"
$ return : int 5 5 3有很多方法可以做到这一点,这取决于你正在寻找的是什么。
更新
虽然它可能不是base R,但tidyverse中的包对于数据争论很有用,并且可以用来轻松地将几个调用串在一起。
install.packages("dplyr")
library(dplyr)
df <- data.frame(Direction = c("???????????-?", "???????????+?", "???????????+?", "???????????-?"), stringsAsFactors = F)
df %>%
mutate(qmark = nchar(gsub("[^?]", "", Direction)),
pos = nchar(gsub("[^+]", "", Direction)),
neg = nchar(gsub("[^-]", "", Direction)),
qminus = qmark-(pos+neg),
total = nchar(Direction))
Direction qmark pos neg qminus total
1 ???????????-? 12 0 1 11 13
2 ???????????+? 12 1 0 11 13
3 ???????????+? 12 1 0 11 13
4 ???????????-? 12 0 1 11 13但是,如果您的数据集有1000万行,那么您可能希望使用基于一些基准testing的stringi。
install.packages("stringi")
library(stringi)
df %>%
mutate(qmark = stri_count(Direction, fixed = "?"),
pos = stri_count(Direction, fixed = "+"),
neg = stri_count(Direction, fixed = "-"),
qminus = qmark-(pos+neg))https://stackoverflow.com/questions/45243728
复制相似问题