r - 交错两列,但与数据框中的其他列
问题描述
我想交错数据帧的两列(将 sd 移动到平均值下方),类似于此处,但我的问题是我在同一个数据帧中有其他列。
我的代码如下所示:
year <- rep(2014:2015, length.out = 10000)
group <- sample(c(0,1,2,3,4,5,6), replace=TRUE, size=10000)
value <- sample(10000, replace = T)
dta <- data.frame(year = year, group = group, value = value)
library(dplyr)
dta2 <- dta %>%
group_by(year, group) %>%
summarize(mean=mean(value), sd=sd(value)) %>%
# round:
dta2[,3:4] <- round(dta2[,3:4], 2)
# add parenthesis around sd:
dta2$sd <- paste0("(", dta2$sd, ")")
# Now I would like to interlace mean and sd:
dta3 <- data.frame(c(rbind(dta2[1:3], dta2[3])))
由于数据框中的其他列,这给了我一个错误。
# This is the output I would like:
解决方案
我建议在 R/dplyr 中做这么多
d1 <- dta2[,c(1,2,4)]
d2 <- dta2[,1:3]
#making the colnames same
colnames(d2) <- colnames(d1)
#changing data type
d2$sd <- as.character(d2$sd)
#creating output
output <- arrange(rbind(d2, d1), year, group)
#changing colname of output table
colnames(output[,3]) <- 'mean (sd in parenthesis)'
output
# A tibble: 28 x 3
# Groups: year [2]
year group sd
<int> <dbl> <chr>
1 2014 0 5058.15
2 2014 0 (2815.17)
3 2014 1 5240.23
4 2014 1 (2871.65)
5 2014 2 5095.8
6 2014 2 (2808.97)
7 2014 3 5112.54
8 2014 3 (2917.15)
9 2014 4 4983.58
10 2014 4 (2917.3)
# ... with 18 more rows
推荐阅读
- r - 转换多列类
- java - 为什么这个线程代码不能在 GUI 上正常工作?[Java Swing] [线程]
- arrays - 使用 jq 替换字典中的数组值
- c# - XSL-FO 文档:在具体的 fo:table-row 中插入 break-before="page" 属性
- python-3.x - 双击不在 html 中的可视元素使 textarea 出现 selenium
- javascript - XHR 加载失败:GET Works 有时我不知道为什么
- python - R BetaExpert 函数的 Python 等效项
- vue.js - vue js事件总线调用很少的事件
- javascript - 返回嵌套json的js递归函数
- java - 需要帮助来了解有关 While 循环条件语句和类型转换的一些基本 Java 概念