Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在列中拆分字符串并计算字符的出现次数_R - Fatal编程技术网

R 在列中拆分字符串并计算字符的出现次数

R 在列中拆分字符串并计算字符的出现次数,r,R,我有一个非常大的文件,dim:47685x10541。在该文件中,第二列中每行的字符之间没有空格,如下所示: 文件#1 Row1 01205201207502102102….. Row2 20101020100210201022….. Row3 21050210210001120120….. 我想对该文件进行一些统计,可能需要删除一些列或行。因此,使用R,我想在第二列中的每两个字符之间添加一个空格,得到如下结果: 文件#2 Row1 0 1 2 0 5 2 0 1 2 0 7 5 0 2

我有一个非常大的文件,dim:47685x10541。在该文件中,第二列中每行的字符之间没有空格,如下所示:

文件#1

Row1 01205201207502102102…..

Row2 20101020100210201022…..

Row3 21050210210001120120…..
我想对该文件进行一些统计,可能需要删除一些列或行。因此,使用R,我想在第二列中的每两个字符之间添加一个空格,得到如下结果:

文件#2

Row1 0 1 2 0 5 2 0 1 2 0 7 5 0 2 1 0 2 1 0 2…..

Row2 2 0 1 0 1 0 2 0 1 0 0 2 1 0 2 0 1 0 2 2…..

Row3 2 1 0 0 0 2 1 0 2 1 0 0 0 1 1 2 0 1 2 0…..
然后,在我完成编辑后,删除第二列中字符之间的空格,这样最终的格式将与
File#1
一样

做这件事的最好和更快的方法是什么?

还更新了列计数寻址。(来自您的评论)

下面是一个使用
tidyr
stringr
的解决方案。但是,这考虑到您的字符串对于column2的长度相等。该解决方案同时提供行和列计数。这是以非常基本的一步一步的方式完成的,也可以通过几行代码来实现

library(stringr)
library(tidyr)

data<-data.frame( Column.1 = c("01205", "20705", "27057"),
                  stringsAsFactors = FALSE)

count<-str_count(data$Column.1) # Get the length of the string in column 2
index<-1:count[1] # Generate an index based on the length

# Count the number of 5 and 7 in each string by row and add it as new column
data$Row.count_5 <- str_count(data$Column.1, "5")
data$Row.count_7 <- str_count(data$Column.1, "7")

new.data <- separate(data, Column.1, into = paste("V", 1:count[1], sep = ""), sep = index)
new.data$'NA' <- NULL
new.data

Column_count_5 <- apply(new.data[1:5],2,FUN=function(x) sum(x == 5))
Column_count_7 <- apply(new.data[1:5],2,FUN=function(x) sum(x == 7))
column_count <- as.data.frame(t(data.frame(Column_count_5,Column_count_7)))

library(plyr)
Final.df<- rbind.fill(new.data,column_count)
rownames(Final.df)<-c("Row1","Row2","Row3", "Column.count_5","Column.count_7")
Final.df

样本数据

data<-data.frame( Column.1 = c("01205", "20705", "27057"),
                  stringsAsFactors = FALSE)

dataAdding spaces似乎与“我想对该文件进行一些统计,可能会删除一些列或行”无关。我们是否在此处设置了一个名称?如果您知道每一列都包含一个字符,正如您的请求所暗示的,则无需将它们分开。你可以按每一个字符串的状态建立索引。你能告诉我怎么做吗。我的目标是查看每一行/每一列中有多少个5和/或7,然后我决定删除或保留每一列或每一行。是否尝试为第2列的值创建一个矩阵,以便每个值都位于单独的列中?
data<-data.frame( Column.1 = c("01205", "20705", "27057"),
                  stringsAsFactors = FALSE)