首页 > 解决方案 > 交错两列,但与数据框中的其他列

问题描述

我想交错数据帧的两列(将 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

解决方案


我建议在 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

在下文中,您可以使用一些包以所需的 html 格式显示表格,如此处或此处所讨论


推荐阅读