R 多变量和行
我的数据集具有以下结构:R 多变量和行,r,sum,line,R,Sum,Line,我的数据集具有以下结构: id amount zipcode cat1 cat1_times cat2 cat2_times 1 1000 1001 0 0 1 7 2 2000 1001 0 0 1 7 3 2300 1002 1 6 1 5 4 1500 1002 1 6 1 5 5
id amount zipcode cat1 cat1_times cat2 cat2_times
1 1000 1001 0 0 1 7
2 2000 1001 0 0 1 7
3 2300 1002 1 6 1 5
4 1500 1002 1 6 1 5
5 2700 1003 1 3 1 5
6 3400 1003 1 3 1 5
Cat1是一个二进制变量,如果某个zipcode中存在类别1的构建,则该变量的值为1。Cat1_times是特定zipcode中1类建筑的数量。
我想计算每条线路的建筑总数(cat1+cat2):
id amount zipcode cat1 cat1_times cat2 cat2_times total_times
1 1000 1001 0 0 1 7 7
2 2000 1001 0 0 1 7 7
3 2300 1002 1 6 1 5 11
4 1500 1002 1 6 1 5 11
5 2700 1003 1 3 1 5 8
6 3400 1003 1 3 1 5 8
我尝试使用sum(cat1\u次,cat2\u次),但每行都得到了相同的结果。使用
stringr
的str\u detect
和rowSums
library(stringr)
df$Total=rowSums(df[,names(df)[str_detect(names(df),'times')]])
df
id amount zipcode cat1 cat1_times cat2 cat2_times Total
1 1 1000 1001 0 0 1 7 7
2 2 2000 1001 0 0 1 7 7
3 3 2300 1002 1 6 1 5 11
4 4 1500 1002 1 6 1 5 11
5 5 2700 1003 1 3 1 5 8
6 6 3400 1003 1 3 1 5 8
使用
stringr
的str\u detect
和rowsumes
library(stringr)
df$Total=rowSums(df[,names(df)[str_detect(names(df),'times')]])
df
id amount zipcode cat1 cat1_times cat2 cat2_times Total
1 1 1000 1001 0 0 1 7 7
2 2 2000 1001 0 0 1 7 7
3 3 2300 1002 1 6 1 5 11
4 4 1500 1002 1 6 1 5 11
5 5 2700 1003 1 3 1 5 8
6 6 3400 1003 1 3 1 5 8
或:
或:
或者,如果您有许多列
numberOfCategories=2
rowSums(df[,paste0('cat',1:numberOfCategories,'_times')])
或者,如果您有许多列
numberOfCategories=2
rowSums(df[,paste0('cat',1:numberOfCategories,'_times')])
使用
base R
df1$total_times <- Reduce(`+`, df1[grep('cat\\d+_times', names(df1))])
df1$total_times
#[1] 7 7 11 11 8 8
df1$total_times使用base R
df1$total_times <- Reduce(`+`, df1[grep('cat\\d+_times', names(df1))])
df1$total_times
#[1] 7 7 11 11 8 8
df1$total\u timesdf$total\u times=df$cat1\u times+df$cat2\u times
应该可以工作。所以简单地说,df$cat1\u times+df$cat2\u times
?…谢谢大家,这两种方法都可以工作,您知道为什么使用sum()函数吗没有工作?df$total\u times=df$cat1\u times+df$cat2\u times
应该可以工作。所以简单地说,df$cat1\u times+df$cat2\u times
?…谢谢大家,这两种方法都可以工作,你知道sum()函数为什么不工作吗?