given table 1, convert to table 2.
I can solve the first part by creating table 1.
library(tidyverse)
grp = c("A", "A", "B", "B")
sex = c("F", "M", "F", "M")
meanL = c(0.22, 0.47, 0.33, 0.55)
sdL = c(.11, .33, .11, .31)
meanR = c(.34, .57, .4, .65)
sdR = c(.08, .33, .07, .27)
data <- as.data.frame(cbind(grp, sex, meanL, sdL, meanR, sdR))
head(data)
The best that I can do is gather all of the data into two columns, one containing the variable and the other containing the values.
data2 <- gather(data, categories, meanL:sdR)
head(data2, n=30)
The current place where I am struggling is in labeling the gender for each reading.
Here is a tidyverse
option:
data %>%
gather(k, v, -grp, -sex) %>%
unite(k, sex, k, sep = ".") %>%
spread(k, v)
# grp F.meanL F.meanR F.sdL F.sdR M.meanL M.meanR M.sdL M.sdR
#1 A 0.22 0.34 0.11 0.08 0.47 0.57 0.33 0.33
#2 B 0.33 0.4 0.11 0.07 0.55 0.65 0.31 0.27
I suggest running the code above line-by-line, to see what each step does. In a nutshell, we reshape data from wide to long, combine columns, and reshape again from long to wide.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.