-2

I need help in a research project problem.

The code problem is: i have a big data frame called FRAMETRUE, and a need to sum certain columns of those rows by row in a new column that I will call Group1.

For example:

head.table(FRAMETRUE)

Municipalities  1989  1990  1991  1992  1993  1994  1995  1996  1997
A                 3     3     5    2     3      4     2     5     3
B                 7     1     2    4     5      0     4     8     9
C                 10    15    1    3     2      NA    2     5     3
D                 7     0     NA   5     3       6    4     5     5
E                 5     1     2    4     0       3    5     4     2

I must sum the values in the rows from 1989 to 1995 in a new column called Group1. like the column Group1 should be

Group1
  22
  23

and so on...

I know it must be something simple, I just don't get it, I'm still learning R

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tnorio
  • 61
  • 1
  • 7

2 Answers2

0

If you are looking for an R solution, here's one way to do it: The trick is using [ combined with rowSums

FRAMETRUE$Group1 <- rowSums(FRAMETRUE[, 2:8], na.rm = TRUE)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

A dplyr solution that allows you to refer to your columns by their names:

library(dplyr)

municipalities <- LETTERS[1:4]
year1989 <- sample(4)
year1990 <- sample(4)
year1991 <- sample(4)
df <- data.frame(municipalities,year1989,year1990,year1991)

# df
  municipalities year1989 year1990 year1991
1              A        4        2        2
2              B        3        1        3
3              C        1        3        4
4              D        2        4        1

# Calculate row sums here
df <- mutate(df, Group1 = rowSums(select(df, year1989:year1991)))

# df
  municipalities year1989 year1990 year1991 Group1
1              A        4        2        2      8
2              B        3        1        3      7
3              C        1        3        4      8
4              D        2        4        1      7
Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36