Sarah H
Sarah H

Reputation: 1

Create a loop to add data to a dataframe from another data frame then plot it

I am pulling in data from a csv that looks like (see below Track1 dataset). I am ignoring all the data in Track2-Track5 of Track1 dataset. There are 461 data points in each channel, 369 channels in each track.

Example dataset: Track1
Channel Track_1 Track_2 … Track_5
1         0.02    0.03  … 0.02
1         0.03    0.02  … 0.06
1         0.01    0.03  … 0.01
2         0.02    0.06  … 0.03
2         0.03    0.02  … 0.06
2         0.01    0.03  … 0.01
…
369       0.03    0.02  … 0.06 
369       0.01    0.03  … 0.01
369       0.02    0.01  … 0.02 

I want to change the data to look like this:

Example dataset: DF
Channel_1 Channel_2 … Channel_369 index
   0.02    0.02     …   0.03      1
   0.03    0.03     …   0.01      2 
   0.01    0.01     …   0.02      3
   …
   0.01    0.03     …   0.04      461

What I've tried to do is assign based on criteria to specific columns, but that requires to type out every line from Track_1 to Track_369. I want to compress and simplify, but I cannot figure it out.

DF$Channel_1 <- Track1[Channel == 1, "Track_1"] 
DF$Channel_2 <- Track1[Channel == 2, "Track_1"]
. . . .
DF$Channel_369 <- Track1[Channel == 369, "Track_1"]

Once the data is in DF, I want to plot all the data against my index. Plot(x values will be Track_[i], y value will be index). So I would like my plot to have 369 lines plotted on one graph without having to write every single line. What I've tried is to manually draw every line on the plot, but that requires to write out every line from Track_1 to Track_369.

plot(DF[c("Channel_1","index")], type = "l", col = 1)
lines(DF[c("Channel_2", "index")], type = "l", col = 2) 
. . .
lines(DF[c("Channel_369", "index")], type = "l", col = 369)

The expected output is a graph that plots all 369 columns of data on one plot. The y axis is "index" column, the x axis is the values within the Track_1 through Track_369 columns.

What I'm looking for is a way to simplify the code so that I'm not repeated the same line of code 369 times. Thank you!

Upvotes: 0

Views: 37

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145870

I think unstack() is what you want:

## Read in sample data
Track = read.table(text = "Channel Track_1 Track_2 Track_5
1         0.02    0.03  0.02
1         0.03    0.02  0.06
1         0.01    0.03  0.01
2         0.02    0.06  0.03
2         0.03    0.02  0.06
2         0.01    0.03  0.01
369       0.03    0.02  0.06 
369       0.01    0.03  0.01
369       0.02    0.01  0.02", header = T)

result = unstack(Track, Track_1 ~ Channel)
names(result) = paste0("Track_", unique(Track$Channel))
result$index = 1:nrow(result)
result
#   Track_1 Track_2 Track_369 index
# 1    0.02    0.02      0.03     1
# 2    0.03    0.03      0.01     2
# 3    0.01    0.01      0.02     3

Upvotes: 1

Related Questions