Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each row in data.table, find column name where value == X

Tags:

r

I have a datatable formatted as follows:

Name X1234 X5555 X3000 X5000 X7500 X8745 X9451 X8338 X8377 Object 1 0+ 0+ 1+ 0+ 0+ 0+ 0+ 0+ 0+ Object 2 1+ 0+ 0+ 0+ 0+ 0+ 0+ 0+ 0+ Object 3 0+ 0+ 0+ 0+ 1+ 0+ 0+ 0+ 0+

My datatable is filled with a couple of hundred rows; let's say Objects 1 to 100. All structured as followed. Each row, and thus Object, contains hundred+ columns. In one of these columns (which names are dynamic, but always start with X) I'm looking for the value 1+. The next step i want to acccomplish is adding an extra column, let's name it Number, and fill it with the column name where the value of the row == 1+.

So, my desired result would be:

Name X1234 X5555 X3000 X5000 X7500 X8745 X9451 X8338 Number Object 1 0+ 0+ 1+ 0+ 0+ 0+ 0+ 0+ X3000 Object 2 1+ 0+ 0+ 0+ 0+ 0+ 0+ 0+ X1234 Object 3 0+ 0+ 0+ 0+ 1+ 0+ 0+ 0+ X7500

In R, what would be the best way to accomplish this? I have looked up and experimented with the functions like apply, which etc, but unfortunally haven't found a working solution yet.

I'm fairly new to developing scripts in R so my apologies if my question isn't clear or simple to answer.

Similar case in Python: Find the column name which has the maximum value for each row

like image 966
rewiind Avatar asked Nov 30 '25 16:11

rewiind


1 Answers

An approach with which:

dat$Number <- names(dat)[which(dat == "1+", arr.ind = TRUE)[ , 2]]
# [1] "X1234" "X3000" "X7500"
like image 172
Sven Hohenstein Avatar answered Dec 02 '25 06:12

Sven Hohenstein



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!