0

I have a data frame df that can be sorted based on one of the columns:

name    day    value
 a       1      0.7
 b       1      0.6
 a       2      1.3
 b       2      3.3

I can use the split function to create different data-frames based on day:

df_new <- split(df, df$day)
day1 <- df_new$`1`
day2 <- df_new$`2`

Which creates

>day1
name     day     value
  a       1       0.7
  b       1       0.6

and

>day2
name     day     value
  a       2       1.3
  b       2       3.3

My actual data has about 60 values in day, and I'd like to create a loop instead of handling this manually... but I don't really know what I'm doing. When I try something like

for (i in 1:60) {
day[i] <- df_new$`[i]`
}

I get the error

Error in day[i] <- df_news$'[i]' : object of type 'closure' is not subsettable

I think I might need to define somewhere that I'm creating a new data-frame that I'm filling with information from the split function. Not sure how to do that.

My end goal is to create a transposed table that will look like this:

name    day1   day2  ... day60
a       0.7    1.3   ...  9.8
b       0.6    3.3   ...  12.3

Which I'll try and make after merging all the separate day1...day60 dataframes together. But maybe there is an easier way to do this all together. Thanks for any help.

moxed
  • 343
  • 1
  • 6
  • 16
  • do you just want to reshape your long format data into wide format? – Nate Oct 12 '16 at 21:26
  • Essentially. I want to make the values in `day`, ie: 1-60, the headers of new columns, and then populate those columns with the corresponding numbers in the `value` column. So that the first dataframe `df` I posted looks like the last one I posted. Am I going about this completely wrong? – moxed Oct 12 '16 at 21:29
  • you definitely are doing it the hard way (see the link to the question above), try this `library(reshape2); dcast(original_df, name ~ day)` – Nate Oct 12 '16 at 21:37
  • This is exactly what I needed. Thanks for your help. I'm new to R and didn't even know the reshape library existed! – moxed Oct 13 '16 at 14:16

0 Answers0