在数据框中的每一行插入一个空白行

时间:2019-02-16 04:51:35

标签: r

我有许多数据帧存储在列表(list_df)中,并且其中一个数据帧具有一列(c1),如下所示:

c1

4

6

1.5

2

3

7.5

1

9

我想计算每两行的总和,并在每隔一行中添加值,并在两者之间留一个空白:

输出:

c1     c2

4

6      10

1.5

2      3.5

3

7.5    10.5

1

9      10

现在我有一个代码来创建列c1中每两行的总和

for(i in seq_along(list_df)){
  list_df[[i]]$c2<-
    rowsum(list_df[[i]][,1], as.integer(gl(nrow(list_df[[i]]), 2, nrow(list_df[[i]]))))
}

但是它抛出了一个错误,因为在这种情况下c1的长度为8,但是新创建的列c2的长度为4。

如何以新创建的列c2的值插入备用行的方式来修改此代码?

谢谢

5 个答案:

答案 0 :(得分:2)

c1 = c(4,6,1.5,2,3,7.5,1,9)
ID = rep(1:(length(c1)/2), each=2)

library(data.table)

DT = data.table(ID,c1)
DT

DT[, sum2 := Reduce(`+`, shift(c1, 0:1)), by = ID]
DT

答案 1 :(得分:2)

您可以使用

public Class PreferredAnswer {
   @JsonProperty("answer[0]") 
   private String answer0;

   @JsonProperty("answer[1]") 
   private String answer1;
}

答案 2 :(得分:1)

这是另一种方式:

lapply(list_df, function(x){

  i = 1
  c2 = vector('numeric')

  while(i <= length(x$c1) ){

    c2[i*2 -1] = NA

    c2[i*2]    = sum(x$c1[i*2-1], x$c1[i*2] )

    i = i + 1
    if( i*2 > length(x$c1)) break
  }

  data.frame(c1 = x$c1, c2)
})

答案 3 :(得分:1)

在看到其他人之后,我不知道我对这种选择有多疯狂,但这是可行的!

df1 <- data.frame(
  c1 = c(4, 6, 1.5, 2, 3, 7.5, 1, 9)
)

dfList <- list(df1, df1)

## DEFINE HELPER
func <- function(x) {  
  result <- c() # initialize an empty list
  for (i in seq_along(x)) {
    if((i %% 2) == 1) { # if row count is odd, NA
      result <- c(result, NA)
    } else { # else add the current value to the previous value
      result <- c(result, x[i] + x[i-1])
    }
  }
  return(result) # return result
}

## APPLY HELPER TO LIST
res <- lapply(dfList, function(x){
  x$c2 <- func(x$c1)
  return(x)
})

答案 4 :(得分:1)

要处理行数可能不偶数的情况,可以尝试以下操作:     图书馆(tidyverse)

df1 <- data.frame(
  c1 = c(4, 6, 1.5, 2, 3, 7.5, 1, 9, 42)
)

# add new column
df1$c2 <- NA_real_

# now split df1 in groups of two and add result
result <- df1 %>%
  group_by(key = cumsum(rep(1:0, length = nrow(df1)))) %>%
  mutate(c2 = if (n() == 2)c(NA, sum(c1)) else sum(c1)) %>%
  ungroup %>%
  select(-key)  # remove grouping variable

> result
# A tibble: 9 x 2
c1    c2
<dbl> <dbl>
  1   4    NA  
2   6    10  
3   1.5  NA  
4   2     3.5
5   3    NA  
6   7.5  10.5
7   1    NA  
8   9    10  
9  42    42  
>