nofunsally
nofunsally

Reputation: 2091

Use columns as groups in R

I have data arranged as below. My groups are in columns, I have two groups illustrated below. My actual data set contains about 15 paired variables.

How can I manipulate this data (an imported csv) in R so that I can compare the two groups? For example if I wanted to make a bargraph (using the sciplot library) bargraph.CI (var_x, group, data=mydata), how can I get these columns to be used as groups?

Time var_x var_y var_x_2 var_y_2 var_z var_z_2 
10:00 2 5 .33 .36 1.1 1.5
10:01 2 6 .34 .35 1.2 1.4
etc

Upvotes: 0

Views: 226

Answers (1)

thelatemail
thelatemail

Reputation: 93813

Here's an answer using reshape in base, though I am sure there are a multitude of ways to tackle this issue.

Firstly, recreate the test data:

test <- read.table(header=TRUE,textConnection("Time var_x var_y var_x_2 var_y_2 var_z var_z_2 
10:00 2 5 .33 .36 1.1 1.5
10:01 2 6 .34 .35 1.2 1.4"))

> test
   Time var_x var_y var_x_2 var_y_2 var_z var_z_2
1 10:00     2     5    0.33    0.36   1.1     1.5
2 10:01     2     6    0.34    0.35   1.2     1.4

Reshape the data and save to a new data.frame

testreshape <- reshape(test,
                   idvar="Time",
                   varying=list(c("var_x","var_x_2"),
                                c("var_y","var_y_2"),
                                c("var_z","var_z_2")),
                   v.names=c("var_x",  "var_y", "var_z"),
                   direction="long")
> testreshape
         Time time var_x var_y var_z
10:00.1 10:00    1  2.00  5.00   1.1
10:01.1 10:01    1  2.00  6.00   1.2
10:00.2 10:00    2  0.33  0.36   1.5
10:01.2 10:01    2  0.34  0.35   1.4

Run the barplot code:

library(sciplot)
bargraph.CI(var_x, time, data=testreshape)

Upvotes: 2

Related Questions