按列值转换数据并更改列名称R.

时间:2017-04-25 19:24:25

标签: r tidyr

我想自动按Z列上的值对变换数据帧进行列绑定,并将Z列中的值添加到新列名称中。

每个Z列唯一元素的行数相同。

示例:

之前的数据

         Date        X        Y Z
1  2013-01-01 1.000000 4.000000 A
2  2013-01-01 1.068966 4.034483 A
3  2013-01-01 1.137931 4.068966 A
4  2013-01-01 1.206897 4.103448 A
5  2013-01-01 1.275862 4.137931 A
6  2013-01-01 1.344828 4.172414 A
7  2013-01-01 1.413793 4.206897 A
8  2013-01-01 1.482759 4.241379 A
9  2013-01-01 1.551724 4.275862 A
10 2013-01-01 1.620690 4.310345 A
11 2013-01-01 1.689655 4.344828 B
12 2013-01-01 1.758621 4.379310 B
13 2013-01-01 1.827586 4.413793 B
14 2013-01-01 1.896552 4.448276 B
15 2013-01-01 1.965517 4.482759 B
16 2013-01-01 2.034483 4.517241 B
17 2013-01-01 2.103448 4.551724 B
18 2013-01-01 2.172414 4.586207 B
19 2013-01-01 2.241379 4.620690 B
20 2013-01-01 2.310345 4.655172 B
21 2013-01-01 2.379310 4.689655 C
22 2013-01-01 2.448276 4.724138 C
23 2013-01-01 2.517241 4.758621 C
24 2013-01-01 2.586207 4.793103 C
25 2013-01-01 2.655172 4.827586 C
26 2013-01-01 2.724138 4.862069 C
27 2013-01-01 2.793103 4.896552 C
28 2013-01-01 2.862069 4.931034 C
29 2013-01-01 2.931034 4.965517 C
30 2013-01-01 3.000000 5.000000 C

之后的数据:

         Date      X.A      Y.A      X.B      Y.B      X.C      Y.C
1  2013-01-01 1.000000 4.000000 1.689655 4.344828 2.379310 4.689655
2  2013-01-01 1.068966 4.034483 1.758621 4.379310 2.448276 4.724138
3  2013-01-01 1.137931 4.068966 1.827586 4.413793 2.517241 4.758621
4  2013-01-01 1.206897 4.103448 1.896552 4.448276 2.586207 4.793103
5  2013-01-01 1.275862 4.137931 1.965517 4.482759 2.655172 4.827586
6  2013-01-01 1.344828 4.172414 2.034483 4.517241 2.724138 4.862069
7  2013-01-01 1.413793 4.206897 2.103448 4.551724 2.793103 4.896552
8  2013-01-01 1.482759 4.241379 2.172414 4.586207 2.862069 4.931034
9  2013-01-01 1.551724 4.275862 2.241379 4.620690 2.931034 4.965517
10 2013-01-01 1.620690 4.310345 2.310345 4.655172 3.000000 5.000000

我知道如何做到这一点。但是我的数据框架更长了#34;所以这会有问题。

samp <- data.frame(Date = rep(as.Date("2013/01/01"), times = 30), X = seq(1,3, length.out = 30), Y = seq(4,5, length.out = 30), Z = c(rep("A", times = 10), rep("B", times = 10),rep("C", times = 10)))
samp
samp2 <- bind_cols(samp[1:10,1:3],samp[11:20,2:3],samp[21:30,2:3])
colnames(samp2) <- c("Date", "X.A", "Y.A", "X.B", "Y.B",  "X.C",  "Y.C")
samp2

1 个答案:

答案 0 :(得分:1)

# Load package
library(tidyverse)

# Create example data
samp <- data.frame(Date = rep(as.Date("2013/01/01"), times = 30), 
                   X = seq(1,3, length.out = 30), 
                   Y = seq(4,5, length.out = 30), 
                   Z = c(rep("A", times = 10), rep("B", times = 10), rep("C", times = 10)))

samp2 <- samp %>%
  mutate(Z = as.character(Z)) %>%
  gather(Parameter, Value, X:Y) %>%
  unite(Info, Parameter, Z, sep = ".") %>%
  group_by(Info) %>%
  mutate(Index = 1:n()) %>%
  spread(Info, Value) %>%
  select(Date, `X.A`, `Y.A`, `X.B`, `Y.B`, `X.C`, `Y.C`, -Index)