假设我有一个x值(本例中为10)和2列的数据框。是否可以打印该数据框并将其输出包装到所需的行数,而不是将其打印为x行? 以下示例包含10个值:
当前输出:
V1 V2
1 -0.54850033
2 -0.41569523
3 1.25346656
4 2.08200119
5 1.18916344
. ..........
10 0.18345154
Desired output:
V1 V2 V1 V2
1 -0.54850033 6 -0.45362345
2 -0.41569523 7 1.23466542
3 1.25346656 8 2.98907097
4 2.08200119 9 0.53153214
5 1.18916344 10 1.43453377
print()中是否有可用于此的选项?
答案 0 :(得分:2)
如果您只想在后半部分打印数据框的一半行,可以尝试使用cbind()
:
df2 <- cbind(df[1:(nrow(df)/2), ], df[(1+(nrow(df)/2)):nrow(df), ])
print(df2)
答案 1 :(得分:2)
dplyr
+ tidyr
的一般解决方案(类似于评论中的@ d.b)。这扩展到任意数量的列(只要你有一个id列)和任意数量的结果行:
library(dplyr)
library(tidyr)
split_df = function(DF, nrows = ceiling(nrow(DF)/2)){
DF %>%
mutate(id = rep(1:nrow(.), each = nrows, len = nrow(.))) %>%
gather(variable, value, -id) %>%
unite(temp, id, variable) %>%
group_by(temp) %>%
mutate(id = 1:n()) %>%
spread(temp, value) %>%
select(-id) %>%
data.frame() %>%
setNames(rep(names(DF), ceiling(nrow(DF)/nrows)))
}
<强>结果:强>
> split_df(df)
V1 V2 V3 V1 V2 V3
1 1 -0.56047565 1.2240818 6 1.7150650 1.7869131
2 2 -0.23017749 0.3598138 7 0.4609162 0.4978505
3 3 1.55870831 0.4007715 8 -1.2650612 -1.9666172
4 4 0.07050839 0.1106827 9 -0.6868529 0.7013559
5 5 0.12928774 -0.5558411 10 -0.4456620 -0.4727914
> split_df(df, 4)
V1 V2 V3 V1 V2 V3 V1 V2 V3
1 1 -0.56047565 1.2240818 5 0.1292877 -0.5558411 9 -0.6868529 0.7013559
2 2 -0.23017749 0.3598138 6 1.7150650 1.7869131 10 -0.4456620 -0.4727914
3 3 1.55870831 0.4007715 7 0.4609162 0.4978505 NA NA NA
4 4 0.07050839 0.1106827 8 -1.2650612 -1.9666172 NA NA NA
> split_df(df, 6)
V1 V2 V3 V1 V2 V3
1 1 -0.56047565 1.2240818 7 0.4609162 0.4978505
2 2 -0.23017749 0.3598138 8 -1.2650612 -1.9666172
3 3 1.55870831 0.4007715 9 -0.6868529 0.7013559
4 4 0.07050839 0.1106827 10 -0.4456620 -0.4727914
5 5 0.12928774 -0.5558411 NA NA NA
6 6 1.71506499 1.7869131 NA NA NA
数据:强>
set.seed(123)
df = data.frame(V1 = 1:10, V2 = rnorm(10), V3 = rnorm(10))