在R中组合大量列

时间:2011-10-07 03:28:53

标签: r dataframe

我有一个包含以下列的数据集

C1, V1, C2, V2, C3, V3.........C1000, V1000

所有列都有相同数量的观察(行)。

如何将上述数据合并到一个只包含C,V列的新数据集中,这些列将包含长格式数据集的所有行?

4 个答案:

答案 0 :(得分:4)

您也可以直接使用reshape R中的base功能。我使用与@Kohske相同的示例

reshape(d, direction = 'long', varying = 1:NCOL(d), sep = "")

答案 1 :(得分:3)

假设您的列确实在C和V之间交替,并且您当前的数据框存储在dat中,这样的内容应该有效:

rs <- data.frame(C = unlist(dat[, seq(1,2000,by = 2)]),
                 V = unlist(dat[, seq(2,2000,by = 2)]))

答案 2 :(得分:3)

以下是使用plyr和reshape2包的示例:

> # sample data
> d <- data.frame(matrix(runif(100), 5, 20))
> names(d) <- paste(c("C", "V"), rep(1:10, each = 2), sep = "")
> d
         C1         V1        C2        V2         C3        V3          C4         V4        C5         V5        C6        V6         C7        V7         C8
1 0.1867699 0.93659453 0.1197284 0.9628986 0.52336647 0.9650141 0.651377738 0.90073030 0.2559667 0.91905240 0.3563512 0.6935289 0.43179306 0.6400699 0.61515316
2 0.7576912 0.30851077 0.8677065 0.4920025 0.51844891 0.1035328 0.338086219 0.49316520 0.2735068 0.31079714 0.7707765 0.7829738 0.18611600 0.4998730 0.31711230
3 0.8104602 0.51727882 0.4034713 0.4545304 0.07993988 0.3806043 0.361723985 0.91731069 0.7836848 0.51605825 0.1664879 0.9997097 0.60784616 0.7576581 0.07144218
4 0.6629312 0.78566815 0.3091202 0.6267486 0.04399409 0.5988425 0.001489632 0.15462250 0.6210522 0.51142738 0.2298060 0.8632633 0.01202089 0.6192330 0.61705098
5 0.3714499 0.03534432 0.1200033 0.5566100 0.15498809 0.7600497 0.668615795 0.07763992 0.1017358 0.07118067 0.4254473 0.5877628 0.20763356 0.7201208 0.56749348
         V8        C9        V9       C10       V10
1 0.4997906 0.1539158 0.5079096 0.4153216 0.5391126
2 0.8372036 0.4995961 0.2236440 0.5060925 0.3148300
3 0.9487363 0.5366132 0.3454843 0.8130159 0.6747609
4 0.8924971 0.6801537 0.1349331 0.5654011 0.4541599
5 0.5704078 0.5948960 0.6172788 0.3661633 0.9945200
> 
> # load library
> library(reshape2)
> library(plyr)
> 
> # make obs. id
> d$id <- 1:nrow(d)
> 
> # melt it to longest format (i.e., 1 obs / 1 row)
> d2 <- melt(d, id = "id")
> 
> # split label into C/N and number
> d3 <- mutate(d2,
+              N = substr(variable, 1, 1),
+              i = as.integer(substr(variable, 2, 100)),
+              variable = NULL)
>              
> # reshape and order the data             
> d4 <- dcast(d3, id+i~N, value_var = "value")
> d4$id <- NULL
> id <- arrange(d4, i)
> head(d4)
  i         C         V
1 1 0.1867699 0.9365945
2 2 0.1197284 0.9628986
3 3 0.5233665 0.9650141
4 4 0.6513777 0.9007303
5 5 0.2559667 0.9190524
6 6 0.3563512 0.6935289

答案 3 :(得分:1)

劫持@Jorans回答,我会尝试。

rs <- data.frame(C = unlist(dat[, grep("C",names(dat))]),
                 V = unlist(dat[, grep("V",names(dat))]))

如果您的C和V不交替,这将涵盖您。