r-拆分一列,计算元素数+求和元素数



我正在处理一些数据,其中一列看起来像

21070808(136(|19995886(87(|21280165(66(

20226255(57(| 21440646(54(

需要明确的是,这是一个单列。不在括号中的每个数字表示出版物id(例如,21070808(,括号中的数字表示该出版物收到的引用次数(例如,出版物21070808收到136次引用(。

对于每一项观察,我想统计一下出版物的数量以及引用的总数。例如,以上面的2个观察结果为例,我想得到2列(column1=发表数量,column2=引用(:

Number of publications - Citations
3          -     289
2          -     111 

我曾试图在R/Stata中寻找解决方案,但无法找到任何解决方案。我想就出版物的数量而言,我可以数出"|"字符并加+1。但对于引用总数,我有点困惑。。。

如有任何帮助,我们将不胜感激。我对R/Stata(甚至Python(漠不关心:(

library(tidyverse)
df %>%
rowid_to_column() %>%
separate_rows(col1, sep = '[|]')%>%
separate(col1, c('num', 'cit'),convert = TRUE, extra = 'drop')%>%
group_by(rowid)%>%
summarise(num = n(), cit = sum(cit))%>%
select(-rowid)
# A tibble: 2 x 2
num   cit
<int> <int>
1     3   289
2     2   111
df<-data.frame(x=c("21070808(136)|19995886(87)|21280165(66)","20226255(57)|21440646(54)"))
df$count<-str_count(df$x, "\|")+1
df$sum<-str_extract_all(df$x, "(?<=\()[^()]*(?=\))")
df$sum<-lapply(df$sum, function(y) sum(as.numeric(y)))
df               
x sum count
1 21070808(136)|19995886(87)|21280165(66) 289     3
2               20226255(57)|21440646(54) 111     2

Regex源匹配括号中的数据-仅匹配括号中字符的模式

这里有一个Stata解决方案。

clear 
input str42 problem 
"21070808(136)|19995886(87)|21280165(66)"
"20226255(57)|21440646(54)"
end 
gen count = strlen(problem) - strlen(subinstr(problem, "|", "", .)) + 1 
* ssc install moss 
moss problem, match("(([0-9]+)") regex 
destring _match*, ignore("(") replace 
egen citations = rowtotal(_match*)
keep problem count citations 
list 
+------------------------------------------------------------+
|                                 problem   count   citati~s |
|------------------------------------------------------------|
1. | 21070808(136)|19995886(87)|21280165(66)       3        289 |
2. |               20226255(57)|21440646(54)       2        111 |
+------------------------------------------------------------+

使用base R

lst1 <- type.convert(regmatches(df$x, gregexpr("(?<=\()\d+", df$x, 
perl = TRUE)), as.is = TRUE)
data.frame(Numer_of_publications = lengths(lst1), Citations = sapply(lst1, sum))
Numer_of_publications Citations
1                     3       289
2                     2       111

最新更新