Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

How to check multiple columns and add sum of 1 column in R

I have a data.frame df

 emp = c("k","j","b","s","sy")
Exp = c(11,10,10,10,10)
Supv1 = c("d","k","j","k","an")
Supv2 = c("a","d","k","d", "a")

df <- data.frame(emp, Exp, Supv1, Supv2)

emp Exp Supv1 Sup2
 k    11  d     a
 j    10  k     d
 b    10  j     k
 s    10  k     d
 sy   10  an    a

emp with expenses and shows emp's reporting level 1 and next higher supv2

now i want to get an outup by chaching each supervisor at level 1 and 2 and the corresponding exp. so that i get the supervisor's total span of control expenses

so after checking column Supv1 and Supv 2 the output to be

Sup  total.exp
d      31  
k      30
j      10
an     10
a      21

I have used multiple group_by and summarise then rbind the output . and then a final summarise to get the above output. is there any apply() family function to do this in a simple way?

question from:https://stackoverflow.com/questions/65933359/how-to-check-multiple-columns-and-add-sum-of-1-column-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use aggregate:

aggregate(list(total.exp=rep(df$Exp, 2))
 , list(Sup=unlist(df[,c("Supv1","Supv2")])), sum)
#  Sup total.exp
#1   a        21
#2  an        10
#3   d        31
#4   j        10
#5   k        30

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...