0

I have the following data frame in R

 DF1<-data.frame("S"=c("A", "B", "C"))
 namelist<-c("A", "B", "C")
 DF1[c("A", "B", "C")]<-c(1,2,3)
 DF1$B<-DF1$B*2

I have created a new column Sum as follows

  DF1$Sum<-0

The resulting dataframe is as follows

 S A B C Sum
 A 1 2 1   0
 B 2 4 2   0
 C 3 6 3   0

I want the values in Sum to be filled in such a way that the values against row A of Sum will be equal to the sum of the entries in column A, and similarly for B and C. The result should be as follows

  S A B C Sum
1 A 1 2 1   6
2 B 2 4 2   10
3 C 3 6 3   6

I have tried the following code

 for( i in 1:nrow(DF1)){
  for( j in namelist){
 DF1$Sum[DF1$S[j][i]]=sum(DF1[,j])
  }}

I am not getting the desired result. I am getting the following output. I request someone to help me here.

  S A B C Sum
1 A 1 2 1   0
2 B 2 4 2   0
3 C 3 6 3   0
Raghavan vmvs
  • 1,213
  • 1
  • 10
  • 29

3 Answers3

3

One dplyr possibility could be:

DF1 %>%
 mutate(sum = colSums(.[-1]))

  S A B C sum
1 A 1 2 1   6
2 B 2 4 2  12
3 C 3 6 3   6

Or the same with base R:

DF1$sum <- colSums(DF1[-1])
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
  • @David Arenburg a nice simplification, thank you :) Honestly, with `dplyr` it's just a fixation, here it's really not important. – tmfmnk Aug 22 '19 at 12:03
1

Here is a more general way to do it with arbitrary sequence of characters, that is if the characters are not in the same order as the columns

tmp=colSums(DF1[,-1])
tmp2=data.frame(S=names(tmp),Sum=tmp)
merge(DF1,tmp2,by="S")
user2974951
  • 9,535
  • 1
  • 17
  • 24
1

Here is a quick loop that accomplished your goal

for(i in 1:nrow(DF1)){
DF1$SUM[i] <- sum(DF1[,i+1])
}
Daniel O
  • 4,258
  • 6
  • 20