0

I have a data frame like this:

feature_id  mouse_number  value
P1001       1             8.55
P1001       2             6.50
P1001       3             2.48
P1001       4             9.01
P1002       1             4.41
P1002       2             4.91
P1002       3             5.86
P1002       4             1.89
...

I want the data to read like:

mouse_number   P1001    P1002   ...
1              8.55     4.41
2              6.50     4.91
3              2.48     5.86
4              9.01     1.89

Please assist, thanks!

Jaap
  • 81,064
  • 34
  • 182
  • 193

3 Answers3

1
df <- read.table(text="feature_id  mouse_number  value
P1001       1             8.55
           P1001       2             6.50
           P1001       3             2.48
           P1001       4             9.01
           P1002       1             4.41
           P1002       2             4.91
           P1002       3             5.86
           P1002       4             1.89",stringsAsFactors=F,header=T)

library(tidyr)
df %>% spread(feature_id,value)
# mouse_number P1001 P1002
# 1            1  8.55  4.41
# 2            2  6.50  4.91
# 3            3  2.48  5.86
# 4            4  9.01  1.89
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
1

You can also use the reshape2 package.

library(reshape2)

dt2 <- dcast(dt, mouse_number ~ feature_id, value.var = "value")
dt2
  mouse_number P1001 P1002
1            1  8.55  4.41
2            2  6.50  4.91
3            3  2.48  5.86
4            4  9.01  1.89

DATA

dt <- read.table(text = "feature_id  mouse_number  value
P1001       1             8.55
                 P1001       2             6.50
                 P1001       3             2.48
                 P1001       4             9.01
                 P1002       1             4.41
                 P1002       2             4.91
                 P1002       3             5.86
                 P1002       4             1.89",
                 header = TRUE, stringsAsFactors = FALSE)
www
  • 38,575
  • 12
  • 48
  • 84
1

Another option is dcast from data.table

library(data.table)
dcast(setDT(dt), mouse_number~feature_id)
#   mouse_number P1001 P1002
#1:            1  8.55  4.41
#2:            2  6.50  4.91
#3:            3  2.48  5.86
#4:            4  9.01  1.89

Or if there are equal number of observations, xtabs from base R can be used

xtabs(value~ mouse_number + feature_id, dt)
akrun
  • 874,273
  • 37
  • 540
  • 662