extract data from only columns matching character strings

后端 未结 2 452
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 03:32

I have a dataset that looks something like this (but much larger)

Jul_08 <- c(1,0,2,0,3)
Aug_08 <- c(0,0,1,0,1)
Sep_08 <- c(0,1,0,0,1)
month<-c(\"Jul         


        
2条回答
  •  走了就别回头了
    2021-01-21 03:39

    You can use lapply :

    value <- unlist(lapply(1:nrow(dataset),
                    function(r){ 
                       dataset[r,as.character(dataset[r,'month'])] 
                    }))
    > value
    [1] 1 0 2 0 3
    

    Or, alternatively :

    value <- diag(as.matrix(dataset[,as.character(dataset$month)]))
    > value
    [1] 1 0 2 0 3    
    

    Then you can cbind the new column as you did in your example.

    Some notes:

    • I prefer unlist(lapply(...)) over sapply since automagic simplification implemented in sapply function tends to surprise me sometimes. But I'm pretty sure this time you can use it without any problem.
    • as.character is necessary only if month column is a factor (as in the example), otherwise is redundant (but I would leave it, just to be safe).

提交回复
热议问题