我在R中有一个数据集,它有多个列,我需要所有列都在同一列中。
以下是示例数据集
Net1 Net2 Net3 Net4 Net5 Net6 Net7 Net8 Net9 Net10 Net11 Net12
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl> <lgl>
1 -18 -30 22 27 16 47 -31 53 -10 NA NA NA
2 -9 53 5 -38 -3 -46 48 19 -47 -27 NA NA 从本质上讲,列是同一事物的所有组。Net1+Net5+Net9都代表相同的东西,所以我需要将它们放在一个专栏中。Net2+Net6+Net10也是如此。Net3+Net7+Net11。最后是Net4+Net8+Net12。
因此,在新的数据帧中,它们不应该是12列,而应该是4列。这就是所需的输出:
Net1 Net2 Net3 Net4
<dbl> <dbl> <dbl> <dbl>
1 -18 -30 22 27
2 16 47 -31 53
3 -10 NA NA NA
4 -9 53 5 -38
5 -3 -46 48 19
6 -47 -27 NA NA 发布于 2020-12-03 10:33:09
下面是另一种tidyverse方法
library(tidyr)
names(df) <- rep(c("Net1", "Net2", "Net3", "Net4"), 3L)
df %>% pivot_longer(everything(), ".value")输出
# A tibble: 6 x 4
Net1 Net2 Net3 Net4
<int> <int> <int> <int>
1 -18 -30 22 27
2 16 47 -31 53
3 -10 NA NA NA
4 -9 53 5 -38
5 -3 -46 48 19
6 -47 -27 NA NA或者如果你想把所有东西都放在一个管道中
df %>%
setNames(rep(c("Net1", "Net2", "Net3", "Net4"), 3L)) %>%
pivot_longer(everything(), ".value")发布于 2020-12-03 10:11:34
这里有一个简单的方法:
col_mat = matrix(1:12, nrow = 4)
col_mat
# [,1] [,2] [,3]
# [1,] 1 5 9
# [2,] 2 6 10
# [3,] 3 7 11
# [4,] 4 8 12
result = as.data.frame(apply(col_mat, 1, function(x) unlist(df[x])))
names(result) = names(df)[col_mat[, 1]]
result
# Net1 Net2 Net3 Net4
# 1 -18 -30 22 27
# 2 -9 53 5 -38
# 3 16 47 -31 53
# 4 -3 -46 48 19
# 5 -10 NA NA NA
# 6 -47 -27 NA NA我使用的是这个示例数据--您可能需要先将逻辑列转换为数字。
df = read.table(text = 'Net1 Net2 Net3 Net4 Net5 Net6 Net7 Net8 Net9 Net10 Net11 Net12
1 -18 -30 22 27 16 47 -31 53 -10 NA NA NA
2 -9 53 5 -38 -3 -46 48 19 -47 -27 NA NA ', header = TRUE)发布于 2020-12-03 10:27:37
下面是一种tidyverse方法:
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = everything()) %>%
group_by(row = ceiling(row_number()/4)) %>%
mutate(name = paste0('Net', 1:4)) %>%
pivot_wider() %>%
ungroup %>%
select(-row)
# Net1 Net2 Net3 Net4
# <int> <int> <int> <int>
#1 -18 -30 22 27
#2 16 47 -31 53
#3 -10 NA NA NA
#4 -9 53 5 -38
#5 -3 -46 48 19
#6 -47 -27 NA NAhttps://stackoverflow.com/questions/65118797
复制相似问题