我有下面的example_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]))
答案 0 :(得分:2)
odd_cols <- as.logical(1:ncol(example_df) %% 2)
result_df <- data.frame(total1 = as.vector(apply(example_df[, odd_cols], 2, na.omit)),
total2 = as.vector(apply(example_df[,!odd_cols], 2, na.omit)))
答案 1 :(得分:1)
以下是创建预期输出的两个选项。
1)我们通过对“&lt; example_df&#39;”的备用列进行子集化来创建2列data.frame
。 (使用逻辑索引),unlist
并删除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
或者只需一步
na.omit(do.call(rbind, Map(cbind, example_df[c(TRUE, FALSE)], example_df[c(FALSE, TRUE)])))
2)循环浏览list
中的列序列,将rbind
list
元素与rbindlist
元素进行子集化library(data.table)
rbindlist(lapply(seq(1, ncol(example_df), by =2), function(i)
example_df[i:(i+1)]))[complete.cases(test1, test2)]
并删除NAs
$xp = 500;
$query = "SELECT name FROM ranks WHERE exp >= ?' LIMIT 1";
$stmt = $db->prepare($query);
$stmt->bind_param("s",$xp);
$stmt->execute();
$stmt->bind_param($name);
while($stmt->fetch()){
if($stmt->num_rows > 0 ){
echo $name;
}
}