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

前端 未结 6 913
礼貌的吻别
礼貌的吻别 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:26

    Not a beautiful answer but it could be useful

    DF <- data.frame(ID=1:3,
                     Type=c('A','A','B'), 
                     Values=c(' 5; 7; 8', '6', ' 2;3')) # this is your df
    
        # split vectors and coercing values to be numeric
        List <- lapply(strsplit(Values, ';'), as.numeric)
    
    # The desired output
        data.frame(ID=rep(ID, sapply(List, length)), 
                   Type=rep(Type, sapply(List, length)),
                   Values =   unlist(List))
     ID Type Values
    1  1    A      5
    2  1    A      7
    3  1    A      8
    4  2    A      6
    5  3    B      2
    6  3    B      3
    

提交回复
热议问题