Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将每两列折叠为最后一组两列_R - Fatal编程技术网

R 将每两列折叠为最后一组两列

R 将每两列折叠为最后一组两列,r,R,我有下面的示例_df,它有4个“集合”列,每个集合中有两个列。我基本上想要一种快速的方法来获取每一组两列,并将数据移动到结果的两列中(如下面的result_df所示,这就是我想要的结果)。有没有关于如何实现自动化的想法 set.seed(20) example_df <- data.frame("test1" = c(rnorm(6), rep(NA, 18)), "test2" = c(rnorm(6), rep(NA, 18)),

我有下面的示例_df,它有4个“集合”列,每个集合中有两个列。我基本上想要一种快速的方法来获取每一组两列,并将数据移动到结果的两列中(如下面的result_df所示,这就是我想要的结果)。有没有关于如何实现自动化的想法

set.seed(20)
example_df <- data.frame("test1" = c(rnorm(6), rep(NA, 18)),
                         "test2" = c(rnorm(6), rep(NA, 18)),
                         "test3" = c(rep(NA, 6), rnorm(6), rep(NA, 12)), "test4" = c(rep(NA, 6), rnorm(6), rep(NA, 12)),
                         "test5" = c(rep(NA, 12), rnorm(6), rep(NA, 6)), "test6" = c(rep(NA, 12), rnorm(6), rep(NA, 6)),
                         "test7" = c(rep(NA, 18), rnorm(6)), "test8" = c(rep(NA, 18), rnorm(6)))

result_df <- data.frame("total1" = c(example_df[c(1:6),1], example_df[c(7:12),3], example_df[c(13:18),5], example_df[c(19:24),7]),
                        "total2" = c(example_df[c(1:6),2], example_df[c(7:12),4], example_df[c(13:18),6], example_df[c(19:24),8]))
set.seed(20)

示例\u df
odd\u cols这里有两个选项用于创建预期输出

1)我们通过对“example_df”(使用逻辑索引)的备用列进行子集设置,创建了一个2列
data.frame
取消列表
并删除NAs

total1 <- na.omit(unlist(example_df[c(TRUE, FALSE)]))
total2 <- na.omit(unlist(example_df[c(FALSE, TRUE)]))
d1 <- data.frame(total1, total2)
row.names(d1) <- NULL

#checking with the OP's output
all.equal(d1, result_df, check.attributes=FALSE)
#[1] TRUE
library(data.table)
rbindlist(lapply(seq(1, ncol(example_df), by =2), function(i) 
        example_df[i:(i+1)]))[complete.cases(test1, test2)]
2)
列表
中循环列的顺序,将“示例”子集,
rbind
列表
元素与
rbindlist
一起删除NAs

total1 <- na.omit(unlist(example_df[c(TRUE, FALSE)]))
total2 <- na.omit(unlist(example_df[c(FALSE, TRUE)]))
d1 <- data.frame(total1, total2)
row.names(d1) <- NULL

#checking with the OP's output
all.equal(d1, result_df, check.attributes=FALSE)
#[1] TRUE
library(data.table)
rbindlist(lapply(seq(1, ncol(example_df), by =2), function(i) 
        example_df[i:(i+1)]))[complete.cases(test1, test2)]

你是对的,一下子做了很多事。感谢您的评论和解决方案!