按间隔Dataframe对行进行求和

时间:2018-04-12 23:21:34

标签: r statistics

我在研究项目问题上需要帮助。

代码问题是:我有一个名为FRAMETRUE的大数据框,需要在一个新列中逐行对这些行的某些列求和,我将称之为Group1。

例如:

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

我必须在名为Group1的新列中对1989年到1995年的行中的值求和。比如Group1应该是

Group1
  22
  23

依旧......

我知道它必须是简单的东西,我只是不明白,我还在学习R

2 个答案:

答案 0 :(得分:0)

如果您正在寻找R解决方案,可以采用以下方法:诀窍是使用List<String> result = list.stream() .peek(System.out::println) .distinct() .sorted(Comparator.comparingInt(s -> Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length())))) .collect(Collectors.toList()); 并结合[

rowSums

答案 1 :(得分:0)

dplyr解决方案,允许您按名称引用列:

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
相关问题