extract data from only columns matching character strings

后端 未结 2 450
爱一瞬间的悲伤
爱一瞬间的悲伤 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:53

    You can use matrix indexing:

    w <- match(month, names(dataset))
    
    dataset$value <- dataset[ cbind(seq_len(nrow(dataset)), w) ]
    

    Here the w vector tells R which column to take the value from and seq_len is used to say use the same row, so the value column is constructed by taking the 1st column in the 1st row, then the 2nd column and 2nd row, 1st column for the 3rd row, etc.

提交回复
热议问题