How to create ID column in R

前端 未结 2 472
春和景丽
春和景丽 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

    0 讨论(0)
  • 2020-12-02 01:18

    If your name column doesn't just contain single letters (or even if it does), you can use:

    dat$id <- as.numeric(as.factor(dat$name))
    

    or, more simply:

    dat$id <- c(as.factor(dat$name))
    

    where dat is your data.frame.

    0 讨论(0)
提交回复
热议问题