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

R 在数据框中每行插入一个空行,r,R,我有许多数据帧存储在列表中,其中一个数据帧有一列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<-

我有许多数据帧存储在列表中,其中一个数据帧有一列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的值通过留空插入到备用行中

谢谢

这是另一种方式:

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)
})
你可以用

df = data.frame(c1 = c(4,6,1.5,2,3,7.5,1,9))
df$c2 = NA
df$c2[c(F,T)] = colSums(matrix(df$c1, 2))
#    c1   c2
# 1 4.0   NA
# 2 6.0 10.0
# 3 1.5   NA
# 4 2.0  3.5
# 5 3.0   NA
# 6 7.5 10.5
# 7 1.0   NA
# 8 9.0 10.0

我不知道在看到其他人后我对这个选择有多疯狂,但它是有效的

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)
})

要处理行数可能不是偶数的情况,可以尝试以下方法: 图书馆管理员

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  
> 

当你说空白值时,你指的是NA值,对吗?是的,插入NA也可以。对于一个非常大的数据集来说,这将非常缓慢。
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  
>