我有一个9行54列不同数字的数据集。我想将前九列中的值组合成R中的一个长列。然后对于以下9列中的每一列都相同,直到我只有6个长列。看起来这应该很容易,但我在网上找到的类似问题都没有适用于我的数据集。
答案 0 :(得分:1)
试试这个。假设您的data.frame
为df
:
as.data.frame(matrix(unlist(df),ncol=6))
答案 1 :(得分:0)
假设你想要连接变量,我将把6个变量分成2乘3而不是54变成6乘9来证明:
library(dplyr) # load package
library(tidyr) # load package
set.seed(1839) # set seed for replication
d <- tibble(x=rnorm(5), y=rnorm(5), z=rnorm(5), # create data frame
a=rnorm(5), b=rnorm(5), c=rnorm(5)) # create data frame
数据框如下所示:
# A tibble: 5 x 6
x y z a b c
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1.0127014 -0.7025836 0.2956671 -0.3563105 1.3232985 -0.367605941
2 -0.6845605 -1.4586245 0.3016737 1.6841862 -0.6978598 1.608783979
3 0.3492607 0.1987113 -0.0945271 1.3073516 -0.3971175 -1.074255857
4 -1.6245010 1.0544690 -0.2790357 0.4352904 0.1711608 0.006136588
5 -0.5162476 -0.7112214 0.1681388 1.4536406 0.6854223 -0.442184403
现在使用unite
功能:
d <- d %>% # take data frame
unite(var1, x:z, sep="; ") %>% # combine with semicolon and space in between
unite(var2, a:c, sep="; ") # combine with semicolon and space in between
结果数据框:
# A tibble: 5 x 2
var1 var2
* <chr> <chr>
1 1.01270138785465; -0.702583610804264; 0.295667113228807 -0.356310525447978; 1.3232984913192; -0.367605940884135
2 -0.684560547695866; -1.45862451298252; 0.301673721520136 1.68418623459335; -0.697859769158927; 1.60878397933222
3 0.349260666732972; 0.198711282685719; -0.0945271007709923 1.3073516257469; -0.397117503476358; -1.07425585717004
4 -1.62450101506933; 1.05446901501249; -0.279035672484018 0.435290405700962; 0.171160804752516; 0.00613658799909723
5 -0.516247631722097; -0.711221362746118; 0.168138783952361 1.45364055160547; 0.685422280037675; -0.442184403125297