Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract data from only columns matching character strings

Tags:

r

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_08","Aug_08","Jul_08","Sep_08","Jul_08")
dataset <- data.frame(Jul_08 = Jul_08, Aug_08 = Aug_08, Sep_08=Sep_08,month=month)

For each row, I would to isolate the value for a select month only as indicated by the "month" field. In other words, for a given row, if the column "month" = Jul_08, then for a new "value" column, I would like to include the datum that pertained to the column "Jul_08" from that row.

In essence, the output would add this value column to the dataset

value<-c(1,0,2,0,3)

Creating this final dataset

dataset.value<-cbind(dataset,value)
like image 549
Luke Avatar asked Jun 01 '26 11:06

Luke


1 Answers

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.

like image 113
Greg Snow Avatar answered Jun 04 '26 09:06

Greg Snow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!