How to create ID column in R

前端 未结 2 471
春和景丽
春和景丽 2020-12-02 00:44

I have a longitudinal data in a long format. I want to create an ID variable based on the variable-column that identifies each observation of my data. How do I do that in R?

2条回答
  •  攒了一身酷
    2020-12-02 01:08

    tc='
    name year var1 var2
    A    1    4    3
    A    2    5    1
    A    3    4    2
    B    1    .    .
    B    2    4    3
    B    3    5    1'
    
    df <- read.table(text=tc, header=T)
    
    df$ID <- match(df$name, LETTERS)
    

    Although is not clear if name is a column or are the rownames of the data frame. If is not a column then try rownames(df) instead of df$name

提交回复
热议问题