reshape dataframe based on a string split in one column in R

前端 未结 6 1061
礼貌的吻别
礼貌的吻别 2020-12-30 12:58

I have the following data structure

ID  Type  Values
1   A     5; 7; 8
2   A     6
3   B     2; 3

and I would like to reshape it to the fol

6条回答
  •  梦谈多话
    2020-12-30 13:19

    The answers so far are great. Here's yet another.

    # The data
    DF <- data.frame(ID=1:3,
                     Type=c('A','A','B'), 
                     Values=c(' 5; 7; 8', '6', ' 2;3'))
    

    This solution uses the colsplit() function from the "reshape2" package. One downside is that it expects you to know the number of resulting columns needed.

    require(reshape2)
    DF2 <- data.frame(DF[-3], colsplit(DF$Values, ";", c("V.1", "V.2", "V.3")))
    na.omit(melt(DF2, id.vars=c("ID", "Type")))
    #   ID Type variable value
    # 1  1    A      V.1     5
    # 2  2    A      V.1     6
    # 3  3    B      V.1     2
    # 4  1    A      V.2     7
    # 6  3    B      V.2     3
    # 7  1    A      V.3     8
    

    From here you can sort and drop columns as required to get your final desired output.

提交回复
热议问题