开发者

creating a new column to indicate variable number of each unique animal

I need to change the format of my current data by creating a new column as "tnum"(first column)to indicate trait/variable numbers and the last column "tval" to indicate each trait value. My current data file (9,000 animals) is similar to this format:

anim <- c(201,202,203,204,205) 
bwt <- c(1.2,1.0,0.9,1.1,1.5)
leng <- c(14,21,18,16,19)
temp <- c(33,34,39,38,37) 
mydf <- data.frame(anim,bwt,leng,temp)

   anim bwt  leng  temp
1  201  1.2   14   33
2  202  1.0   21   34
3  203  0.9   18   39
4  204  1.1   16   38
5  205  1.5   19   37

Trait 1 = bwt, trait 2 = leng, and trait 3 = temp. This what I am looking for:

tnum    anim   tval
 1      201    1.2
 2      201    14
 3      201    33
 1      202    1.0
 2      202    21
 3      202    34
 1      203    0.9
 2      203    18
 3      203    39
 1      204    1.1
 2      204    16
 3      204    38
 1   开发者_StackOverflow社区   205    1.5
 2      205    19
 3      205    37

Any help would be appreciated.

Baz


library("reshape")
m <- melt(mydf, id.vars="anim")
m
   anim variable value
1   201      bwt   1.2
2   202      bwt   1.0
3   203      bwt   0.9
4   204      bwt   1.1
5   205      bwt   1.5
6   201     leng  14.0
7   202     leng  21.0
8   203     leng  18.0
9   204     leng  16.0
10  205     leng  19.0
11  201     temp  33.0
12  202     temp  34.0
13  203     temp  39.0
14  204     temp  38.0
15  205     temp  37.0

and please format your code better next time. its simple.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜