我有一個長表格式的資料框,如下所示:
mydf <- data.frame(id = c(123, 123, 123, 123, 123),
name =c("test_2001", "test_2002", "test_2003", "test_2004", "test_2005"),
value = c(15, 20, 25, 30, 35))
mydf
#> id name value
#> 1 123 test_2001 15
#> 2 123 test_2002 20
#> 3 123 test_2003 25
#> 4 123 test_2004 30
#> 5 123 test_2005 35
現在,我想從列name中拆分屬性,這樣我就可以洗掉這些數值并將它們存盤在名為 的另一列中year,輸出如下:
desired <- data.frame(id = c(123, 123, 123, 123, 123),
name =c("test", "test", "test", "test", "test"),
year =c(2001:2005),
value = c(15, 20, 25, 30, 35))
desired
#> id name year value
#> 1 123 test 2001 15
#> 2 123 test 2002 20
#> 3 123 test 2003 25
#> 4 123 test 2004 30
#> 5 123 test 2005 35
考慮到我必須將此更改應用于大量資料,如何自動執行此步驟?
uj5u.com熱心網友回復:
基數R
cbind(mydf, strcapture("(.*)_(.*)", mydf$name, list(name="", year=1L)))
# id name value name year
# 1 123 test_2001 15 test 2001
# 2 123 test_2002 20 test 2002
# 3 123 test_2003 25 test 2003
# 4 123 test_2004 30 test 2004
# 5 123 test_2005 35 test 2005
dplyr/tidyr
library(dplyr)
library(tidyr)
mydf %>%
separate(name, into = c("name", "year"), sep = "_")
# id name year value
# 1 123 test 2001 15
# 2 123 test 2002 20
# 3 123 test 2003 25
# 4 123 test 2004 30
# 5 123 test 2005 35
(注意,有了這個,year是一個字串,可以用 轉換為整數as.integer。)
資料表
library(data.table)
as.data.table(mydf)[, c("name", "year") := tstrsplit(name, "_")][]
# id name value year
# <num> <char> <num> <char>
# 1: 123 test 15 2001
# 2: 123 test 20 2002
# 3: 123 test 25 2003
# 4: 123 test 30 2004
# 5: 123 test 35 2005
(同樣,year這里仍然是一個字串。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/378695.html
上一篇:做雙圖例時如何添加條件陳述句
