[R] Splitting data frame into columns with dplyr
Thierry Onkelinx
thierry.onkelinx at inbo.be
Thu Oct 1 15:24:46 CEST 2015
Dear Michael,
You'll need a combination of dplyr and tidyr
library(dplyr)
library(tidyr)
data.frame(id = rep(1:3, 2), z = rep(c("A", "B")), x = 1:6, y = 7:12) %>%
arrange(z) %>%
gather(variable, value, -z, -id) %>%
mutate(newcol = paste(z, variable, sep = ".")) %>%
select(-z, -variable) %>%
spread(newcol, value)
ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature and
Forest
team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
Kliniekstraat 25
1070 Anderlecht
Belgium
To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to say
what the experiment died of. ~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data. ~ Roger Brinner
The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey
2015-10-01 14:42 GMT+02:00 <Michael.Laviolette op dhhs.state.nh.us>:
>
> I have a data frame with a structure similar to the following. The variable
> z is a grouping variable; x and y are measurement variables.
>
> library(dplyr)
> df <- data.frame(z = rep(c("A", "B")), x = 1:6, y = 7:12) %>%
> arrange(z)
>
> z x y
> 1 A 1 7
> 2 A 3 9
> 3 A 5 11
> 4 B 2 8
> 5 B 4 10
> 6 B 6 12
>
> I need to reshape into one column for each group-measurement combination as
> below. Preferably using dplyr functions, how can I get to this?
>
> A.x A.y B.x B.y
> 1 1 7 2 8
> 2 3 9 4 10
> 3 5 11 6 12
>
> Thanks,
> M.L.
>
> ______________________________________________
> R-help op r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list