-1

Apologies for any issues but this is my first query on this site.

I'm trying to create a new column in my dataframe which contains a new value, the name of the column that contains the lowest value across that row (each row is an individual sample). I need this new column lowest_col_name to be created and added to the dataframe. My dataframe contains many columns and I only want it to look for this lowest value within 4 individual columns (labelled "High", "Good", "Moderate" and "Poor".

mydata[, c("lowest_col_name")] = names(mydata)[apply(mydata[,c("high","good","moderate","poorbad")], MARGIN = 1, FUN = which.min)]

Any help would be great!

I've tried many iterations of code similar to this but have had no luck.

This piece of code runs but gives me back the names of non-numeric and empty columns, columns that are not among the 4 specified. If i create a smaller dataframe with only the "High", "Good", "Moderate" and "Poor" values, and then run the code, it seems to work but i need the other information included in my output.

I don't want to split and re-join the dataframes as this would cause other unrelated issues with how I handle the data.

yuliaUU
  • 1,581
  • 2
  • 12
  • 33
Roonin
  • 14
  • 4
  • Check if [this](https://stackoverflow.com/questions/70171761/how-do-i-add-a-column-to-a-data-frame-consisting-of-minimum-values-from-other-co) works. Similar questions are already answered multiple times here check them before asking a new question here. – Mohan Govindasamy Jan 30 '23 at 13:31
  • Welcome to SO. You maximize your chance of getting a useful answer if you provide a minimal reproducible example. This [post](https://stackoverflow.com/help/minimal-reproducible-example)  may help. – yuliaUU Jan 30 '23 at 21:23

1 Answers1

0

You are on the right track:

cols = c("high", "good", "moderate", "poor")
df[["lowest_col"]] = apply(df[,c(cols)],1, \(k) cols[which.min(k)])

Output:

  No.     Lake_name Lake_code Survey_date      high       good  moderate      poor
1   1      Ardderry        NA          NA  2.381699  1.1563165  4.261368  4.203357
2   2         Barra        NA          NA  7.942011 13.2606505 15.610125 31.038136
3   3 Macnean lower        NA          NA 80.136657 72.4713182 54.212898 43.967159
4   4       Maumwee        NA          NA  2.983957  0.8674345  2.126441  6.971267
5   5   Ballyquirke        NA          NA 97.435834 88.7457862 69.260245 55.065063
  DA_classification_score lowest_col
1               1.1563165       good
2               7.9420112       high
3              43.9671593       poor
4               0.8674345       good
5              55.0650630       poor
langtang
  • 22,248
  • 1
  • 12
  • 27