看板 R_Language 關於我們 聯絡資訊
[問題類型]: 意見調查(我對R 有個很棒的想法,想問問大家的意見) [軟體熟悉度]: 入門(寫過其他程式,只是對語法不熟悉) [問題敘述]: 要將寬型的資料轉成長型的資料,但是要合併成的新變項有兩個 以iris為例 本來iris的資料長這樣 | Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | |:------------:|:-----------:|:------------:|:-----------:|:-------:| | 5.1 | 3.5 | 1.4 | 0.2 | setosa | | 4.9 | 3.0 | 1.4 | 0.2 | setosa | | 4.7 | 3.2 | 1.3 | 0.2 | setosa | | 4.6 | 3.1 | 1.5 | 0.2 | setosa | 我想要轉成 | Species | SorP.x | Length | Width | |:-------:|:------------:|:------:|:-----:| | setosa | Sepal | 5.1 | 3.5 | | setosa | Sepal | 5.1 | 3.0 | | setosa | Pepal | 5.1 | 3.2 | | setosa | Pepal | 5.1 | 3.1 | | setosa | Sepal | 5.1 | 3.6 | 目前我想到的作法是先弄出兩個長期的資料,一個是Length另一個是Width 然後再把兩個merge起來,請問大家有沒有什麼其他的方法?可以不用先弄成兩個資料? [程式範例]: data("iris") head(iris) library(tidyr);library(dplyr) aa <- merge( gather(iris[-c(2,4)],key = SorP, value = Length, Sepal.Length, Petal.Length), gather(iris[-c(1,3)],key = SorP, value = Width, Sepal.Width, Petal.Width), by.x = "Species", by.y = "Species") [環境敘述]: R version 3.3.0 (2016-05-03) Platform: x86_64-apple-darwin13.4.0 (64-bit) Running under: OS X 10.11.6 (El Capitan) [關鍵字]: 資料格式、tidyr -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.225.248.40 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1471053111.A.7A5.html
yomilin: 用spread應該可以哦 08/13 13:01
DrRd: 感謝提示 08/13 21:52