R:将变量的级别分成两个变量

时间:2017-01-12 23:01:20

标签: r

我有一个data.frame,有12个观察值和3个变量

df <- read.table(text = c("
SiteID  scenario    value 
site1   measured_raw21  55
                          site1 measured_raw22  60
                          site1 simulated_raw21 54
                          site1 simulated_raw22 59
                          site1 measured_adj21  23
                          site1 measured_adj22  27
                          site1 simulated_adj21 22
                          site1 simulated_adj22 28
                          site1 meaured_0.5 40
                          site1 meaured_0.8 55
                          site1 simulated_0.5   40
                          site1 simulated_0.8   57"), header =T)

在这个df中,我想将scenario的级别分成两列

> df
   SiteID        scenario value
1   site1  measured_raw21    55
2   site1  measured_raw22    60
3   site1 simulated_raw21    54
4   site1 simulated_raw22    59
5   site1  measured_adj21    23
6   site1  measured_adj22    27
7   site1 simulated_adj21    22
8   site1 simulated_adj22    28
9   site1     meaured_0.5    40
10  site1     meaured_0.8    55
11  site1   simulated_0.5    40
12  site1   simulated_0.8    57

输出应该是这样的

SiteID  scenario    scenario1   value 
site1   measured    raw21       55
site1   measured    raw22       60
site1   simulated   raw21       54
site1   simulated   raw22       59
site1   measured    adj21       23
site1   measured    adj22       27
site1   simulated   adj21       22
site1   simulated   adj22       28
site1   meaured     0.5         40
site1   meaured     0.8         55
site1   simulated   0.5         40
site1   simulated   0.8         57

有关如何在R中执行此操作的任何建议吗?

2 个答案:

答案 0 :(得分:2)

tidyr图书馆救援:

library(tidyr)
df <- separate(df, col = scenario, into = c("scenario","scenario1"), sep = "_")

答案 1 :(得分:1)

以下是使用base R

的选项
cbind(df[-2], read.table(text=as.character(df$scenario), sep="_", 
         header=FALSE, col.names = c("scenario", "scenario1")))]c(1, 3, 4, 2)]