簡體   English   中英

使用R將數據集中的多個列重新排列到一列中

[英]Re-arrange multiple columns in a data set into one column using R

我想將我的一個數據集中的三列組合成一個變量名為“al_anim”的列,並刪除任何重復項,將值(動物ID)從最低到最高排序,並將每個動物從1到N重新編號為變量名“new_id”。

 anim1 <- c(1456,2569,5489,1456,4587)
 anim2 <- c(6531,6987,6987,15487,6531)
 anim3 <- c(4587,6548,7894,3215,8542)
 mydf <- data.frame(anim1,anim2,anim3)

任何幫助將非常感謝!

巴茲

使用示例中的mydf

mydf <- data.frame(anim1, anim2, anim3)

堆疊數據:

sdf <- stack(mydf)

然后使用unique()計算唯一元素

uni <- unique(sdf[, "values"])

然后這將使他們成為一個新的動物id

new_id <- as.numeric(as.factor(sort(uni)))

這會給:

> new_id
 [1]  1  2  3  4  5  6  7  8  9 10 11

然而,這完全是微不足道的; seq_along(uni)讓你更容易到達那里。 所以我想知道你是否想要

newdf <- data.frame(anim = sort(uni), new_id = seq_along(uni))
merge(sdf, newdf, by.x = "values", by.y = "anim")

這使:

> merge(sdf, newdf, by.x = "values", by.y = "anim")
   values   ind new_id
1    1456 anim1      1
2    1456 anim1      1
3    2569 anim1      2
4    3215 anim3      3
5    4587 anim1      4
6    4587 anim3      4
7    5489 anim1      5
8    6531 anim2      6
9    6531 anim2      6
10   6548 anim3      7
11   6987 anim2      8
12   6987 anim2      8
13   7894 anim3      9
14   8542 anim3     10
15  15487 anim2     11

您的問題中存在一定程度的含糊不清,可以通過給出預期的結果/輸出來緩解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM