繁体   English   中英

将 R 中的两列合并为一长列

[英]Combining Two Columns in R into one long column

我在 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 也一样。 网3+网7+网11。 最后是Net4+Net8+Net12。

因此,在新的 dataframe 中,它们应该是 4,而不是 12 列。 这是所需的 output:

   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      

这是另一种tidyverse方法

library(tidyr)

names(df) <- rep(c("Net1", "Net2", "Net3", "Net4"), 3L)
df %>% pivot_longer(everything(), ".value")

Output

# 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")

这是一个简洁的方法:

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)

这是一个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    NA

这是一个简单的基本 R 方法:

data.frame(matrix(t(df), ncol = 4, byrow = TRUE, dimnames = list(NULL, names(df)[1:4])))
#   Net1 Net2 Net3 Net4
# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM