繁体   English   中英

在 R 中递归地加入列

[英]join columns recursively in R

您好,我有一个包含 245 列的数据框,但是要添加一些集合并生成新列,请尝试递归地执行以下操作

cl1<-sample(1:4,10,replace=TRUE)
cl2<-sample(1:4,10,replace=TRUE)
cl3<-sample(1:4,10,replace=TRUE)
cl4<-sample(1:4,10,replace=TRUE)
cl5<-sample(1:4,10,replace=TRUE)
cl6<-sample(1:4,10,replace=TRUE)
dat<-data.frame(cl1,cl2,cl3,cl4,cl5,cl6)

我的意图是将第 1 列与第 3 列和第 5 列相加,同样将第 2 列与第 4 列和第 6 列相加,最后获得具有两列的 dataframe

在此处输入图像描述

你应该付给我类似的东西在此处输入图像描述

我已经编写了以下代码



revisar<- function(a){
  todos = list()
  i=1
  j=3
  l=5
  k=1
  while(i<=2 ){
    
    cl<-a[,i]
    cl2<-a[,j]
    cl3<-a[,l]
    cl[is.na(cl)] <- 0
    cl2[is.na(cl2)] <- 0
    cl3[is.na(cl3)] <- 0
    
    colu<-cl+cl2+cl3
    
    col<-cbind(colu,colu)
    
    i<-i+1
    j<-j+1
    l<-l+1
    k<-k+1
  }
 
  return(col)
}

事实证明,它只返回重复两次的第 2 列,我必须复制相同的内容才能加入这 245 列。 7

我想知道示例失败的原因

底座 R

文字编程:

with(dat, data.frame(s1 = cl1+cl3+cl5, s2 = cl2+cl4+cl6))
#    s1 s2
# 1   7 11
# 2   7  7
# 3   4 11
# 4   4 10
# 5   9  8
# 6  12  5
# 7   7  6
# 8   7 10
# 9   4  9
# 10  6  5

以编程方式,

L <- list(s1 = c(1,3,5), s2 = c(2,4,6))
out <- data.frame(lapply(L, function(z) do.call(rowSums, list(as.matrix(dat[,z])))))
out
#    s1 s2
# 1   7 11
# 2   7  7
# 3   4 11
# 4   4 10
# 5   9  8
# 6  12  5
# 7   7  6
# 8   7 10
# 9   4  9
# 10  6  5

dplyr

library(dplyr)
dat %>%
  transmute(
    s1 = rowSums(cbind(cl1, cl3, cl5)),
    s2 = rowSums(cbind(cl2, cl4, cl6))
  )

或以编程方式使用purrr

purrr::map_dfc(L, ~ rowSums(dat[, .]))

数据

set.seed(42)
# your `dat` above

这是另一种通用方法:

在这里,我们将所有不均匀的列 -> s1 和所有的偶数列 -> s2 相加:

library(dplyr)

dat %>%
  rowwise() %>% 
  mutate(s1 = sum(c_across(seq(1,ncol(dat),2)), na.rm = TRUE),
         s2 = sum(c_across(seq(2,ncol(dat),2)), na.rm = TRUE))
     cl1   cl2   cl3   cl4   cl5   cl6    s1    s2
   <int> <int> <int> <int> <int> <int> <int> <int>
 1     1     1     3     2     3     2     7     5
 2     2     4     1     4     2     3     5    11
 3     2     2     2     2     1     3     5     7
 4     2     4     4     3     1     4     7    11
 5     2     4     4     3     2     2     8     9
 6     3     3     3     2     2     2     8     7
 7     2     1     1     2     1     4     4     7
 8     2     4     1     3     2     3     5    10
 9     3     1     1     2     3     4     7     7
10     2     4     1     3     4     4     7    11

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM