-4

As the title says, I have a column 'values' that has a list of values for each entry. I want to find the minimum value in the list for each row and append it in a new column. Below is what I've tried (among other things) based on this answer Extract the maximum value within each group in a dataframe. Unfortunately, I only manage to find the minimum of the entire column and apply that same minimum to every row.

df <- df[,'minVal' := min(unlist(df$values))]
Jaap
  • 81,064
  • 34
  • 182
  • 193
Fonti
  • 1,169
  • 2
  • 9
  • 14
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Nov 09 '17 at 20:19
  • It would be easier to help you if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data (ideally a `dput()` of some sort). – MrFlick Nov 09 '17 at 20:20
  • My apologies, its been a while since I've used Stackoverflow. Eric has answered below and his example captures the model. – Fonti Nov 09 '17 at 21:05

1 Answers1

2

As you've discovered, min will return the minimum for the whole column. Sounds like each entry is a list, and when you unlist it you will get a vector of all values, of which min will return the minimum.

Instead, you could apply min to each entry in the list, to get the minimum.

In addition, the := assignment is in place. You don't need to assign back to df using <-, and within the data.table you can refer to columns directly, don't use df$values.

Try this:

library(data.table)

df <- data.table(a = 1:3, values = list(1:6, 2:4, 9:11))
df[, minVal := sapply(values, min)]
df
#    a      values minVal
# 1: 1 1,2,3,4,5,6      1
# 2: 2       2,3,4      2
# 3: 3     9,10,11      9
Eric Watt
  • 3,180
  • 9
  • 21