开发者

changing variable values into new variables in r

开发者 https://www.devze.com 2023-03-19 05:09 出处:网络
I have a data set with about 600 animals with this structure: anim <- c(1,1,1,1,1,2,2,2,2) point <- c(1,2,3,4,6,3,4,5,6)

I have a data set with about 600 animals with this structure:

anim <- c(1,1,1,1,1,2,2,2,2)
point <- c(1,2,3,4,6,3,4,5,6)
temp <- c(38.8,38.5,33.2,33.5,37.2,36.2,36.5,36.0,37.8)
mydf <- data.frame(anim,point,temp)

anim point temp
1     1    38.8
1     2    38.5
1     3    33.2
1     4    33.5
1     6    37.2
2     3    36.2
2     4  开发者_JS百科  36.5
2     5    36.0
2     6    37.8

The variable "point" contains different measuring points (temperature) on an animal and I need to have these measuring points (1,2,3,4,5,6) as new variables such that 1=bel,2=ber,3=le,4=re,5=ey,6=cr. Note, that some points may not appear or measured and therefore NA should be put in.

mynewdf should look like this:

anim  bel   ber   le    re    ey    cr
1     38.8  38.5  33.2  33.5  NA    37.2
2     NA    NA    36.2  36.5  36.0  37.8

I hope that my question is clear enough and any help would be very much appreciated.

EDITED:

This is an extract from my actual data set:

head(irpig,n=25)

head(irpig,n=25) dam anim point temp 1 1A0331 20584 1 37.9 2 1A0331 20584 2 37.7 3 1A0331 20584 3 34.3 4 1A0331 20584 4 35.8 5 1A0331 20584 6 37.6 6 1A0331 20585 2 38.7 7 1A0331 20585 4 36.4 8 1A0331 20585 6 38.0 9 1A0331 20586 1 39.0 10 1A0331 20586 2 39.8 11 1A0331 20586 3 37.9 12 1A0331 20586 4 38.0 13 1A0331 20586 6 38.5 14 1A0331 20587 1 39.3 15 1A0331 20587 2 38.9 16 1A0331 20587 3 39.4 17 1A0331 20587 4 38.6 18 1A0331 20587 6 39.4 19 1A0331 20588 1 39.6 20 1A0331 20588 2 39.2 21 1A0331 20588 3 38.9 22 1A0331 20588 4 38.0 23 1A0331 20588 6 39.6 24 1A0331 20589 1 38.1 25 1A0331 20589 2 38.7

Baz


Here is one solution. It uses the dcast function from reshape2 library by Hadley Wickham

mydf$point = as.factor(mydf$point)
levels(mydf$point)  = c("bel", "ber", "le", "re",  "ey", "cr")

library(reshape2)
dcast(mydf, anim ~ point)

  anim  bel  ber   le   re ey   cr
1    1 38.8 38.5 33.2 33.5 NA 37.2
2    2   NA   NA 36.2 36.5 36 37.8
0

精彩评论

暂无评论...
验证码 换一张
取 消