Home > Mobile >  Practice question I'm struggling with using Rstudio
Practice question I'm struggling with using Rstudio

Time:04-28

The question is:

"Replace ??? by a single line of code so that sleep has one row per subject, and the following 11 variables: Subject (the subject ID), X0 (reaction time at day 0), X1 (reaction time at day 1), ..., X9 (reaction time at day 9)."

This is the code provided:

data <- read.csv("sleep.csv")
data2 <- read.csv("sleepGeneratedIn2C.csv")

subjectUnique <- sort(unique(data$Subject))
sleep <- data.frame(subject=subjectUnique, X0=NA, rbind(rep(NA, 9)))
n <- length(subjectUnique)
for(i in (1:n)) {
  for(j in (0:9)) {
    sleep[i,j 2] <- ???
   }
}

Here are images of the data sets: sleep.csv sleepGeneratedIn2C.csv

CodePudding user response:

Unfortunately, I don't know to do it with loop. But I got a dplyr solution for you.

require(tidyverse) 

Example dataset:

# A tibble: 30 x 3
   reaction   day subject
      <int> <int>   <dbl>
 1      343     1     308
 2      319     2     308
 3      260     3     308
 4      322     4     308
 5      384     5     308
 6      421     6     308
 7      337     7     308
 8      283     8     308
 9      341     9     308
10      378    10     308
# ... with 20 more rows

The code:

df_example %>%
  spread(., key = day, value = reaction) %>%
  janitor::clean_names()

The output:

# A tibble: 3 x 11
  subject    x1    x2    x3    x4    x5    x6    x7    x8    x9   x10
    <dbl> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1     308   343   319   260   322   384   421   337   283   341   378
2     309   365   408   420   294   315   284   443   351   350   442
3     310   305   276   372   262   453   249   449   358   430   382
  •  Tags:  
  • r
  • Related