将列分为R中的范围

时间:2016-03-11 10:24:50

标签: r

我想知道如何将列分成范围。样本数据如下。

Name    V1.1    V1.2    V2.1    V2.2    V3.1    V3.2
AAA    Skill1   Level3  skill2 Level1   Skill3 Level2
BBB    Skill1   Level4  Skill2 Level2   Skill3 Level1

预期输出

Name  Level1 Level2  Level3  Level4
AAA   Skill2 Skill3  Skill1   NA
BBB   Skill3 Skill2  NA       Skill1

只能将代码写入输入。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

我们可以使用melt/dcast

library(data.table)
dcast(melt(setDT(df1), measure= list(seq(2, ncol(df1), by =2), 
    seq(3, ncol(df1), by=2))), Name~value2, value.var='value1')
#     Name Level1 Level2 Level3 Level4
#1:  AAA skill2 Skill3 Skill1     NA
#2:  BBB Skill3 Skill2     NA Skill1

数据

df1 <- structure(list(Name = c("AAA", "BBB"),
 V1.1 = c("Skill1", "Skill1"
), V1.2 = c("Level3", "Level4"), V2.1 = c("skill2", "Skill2"), 
V2.2 = c("Level1", "Level2"), V3.1 = c("Skill3", "Skill3"
), V3.2 = c("Level2", "Level1")), .Names = c("Name", "V1.1", 
"V1.2", "V2.1", "V2.2", "V3.1", "V3.2"),
 class = "data.frame", row.names = c(NA, -2L))