R中的Sum(非相邻)行

时间:2018-05-12 17:17:05

标签: r

抱歉这个基本问题。我搜索了30分钟,但没有发现任何对我有用的东西,所以我冒冒险去问它!

想象一下这样的数据框

X1 X2 X3 X4
 1 12  4  6
 5  4 11  2
 2 19 21  2

我想获得非相邻行的总和 - 1和3,所以有这样的df;

X1 X2 X3 X4
 1 12  4  6
 5  4 11  2
 2 19 21  2
 3 31 25  8

我该怎么做?

我尝试了所有(原始数据框有19行和66列);

exampleframe1[20,] <- rbind(exampleframe1[19,] + exampleframe1[16,])
exampleframe1[20,] <- rowsum(exampleframe1[19,], exampleframe1[16,])
exampleframe1[20,] <- exampleframe1[19,] + exampleframe1[16,]

提前致谢!

3 个答案:

答案 0 :(得分:1)

正如评论中所建议的那样,您可以简单地将奇数行相加:

val a = Array("woot","yeah","ok then").sorted.reverse

样本数据

rbind(df, colSums(df[seq(1, nrow(df), 2), ]))

#  X1 X2 X3 X4
#1  1 12  4  6
#2  5  4 11  2
#3  2 19 21  2
#4  3 31 25  8

答案 1 :(得分:0)

样本数据:

df <- data.frame(X1 = c(1,5,2), X2 = c(12,4,19), X3 = c(4,11,21), X4 = c(6,2,2))

索引行并添加:

df[4,] <- df[1,] + df[3,]

> df
  X1 X2 X3 X4
1  1 12  4  6
2  5  4 11  2
3  2 19 21  2
4  3 31 25  8

desired_rows <- seq(1,3,2) # can be c(1,4,16,17,20,...) with no pattern

> df[desired_rows,] # subset desired rows only
  X1 X2 X3 X4
1  1 12  4  6
3  2 19 21  2

> colSums(df[desired_rows,]) # add desired rows only
 X1 X2 X3 X4 
3 31 25  8

> rbind(df, colSums(df[desired_rows,])) # one-liner to add adjacent rows as desired
  X1 X2 X3 X4
1  1 12  4  6
2  5  4 11  2
3  2 19 21  2
4  3 31 25  8

答案 2 :(得分:0)

您可以使用tidyverse方法。

需要(tidyverse)

  df %>% 
    #To get the index of the rows. 
    rownames_to_column("Index") %>%
    #Creating new variable for even and odd rows
    mutate(rowType = ifelse(as.numeric(Index) %% 2 == 0, "even", "odd")) %>% 
    #Delete the index var as we don't need it anymore. 
    select(-Index) %>%
    #Gather and sum by rowType - even/odd row
    gather(Var, value, -rowType) %>% 
    group_by(rowType) %>% 
    summarise(Total = sum(value, na.rm = TRUE))

结果:

  rowType Total
  <chr>   <dbl>
1 even      22.
2 odd       67.