Convert a dataframe into a named/numeric vector


In the package IsoSpecR, the first argument is of the function IsoSpecify is molecule = molecule = c(C=10,H=22,O=1, N=22); a named vector.
I need to apply this function over many set of values, but I have my data as a dataframe.

mydata1 <- data.frame(C= c(10,2,6), H= c(5,12,1), O= c(2,1,1), N= c(22,22,1))
I have also my data as follows:
mydata2 <- data.frame(iso = c("C= 10, H= 5, O=2, N=22", "C= 2, H= 12, O= 1, N=22", "C= 6, H= 1, O= 1, N=1"))

if I want to use map function:
map(mydata, IsoSpecify( molecule = .x , stopCondition = .9999 )
or a for loop:

for i in seq_along(iso){
res [[i]] <- IsoSpecify(molecule = data[[i]], stopCondition = .9 )

I get the following error:

Error in Rinterface(molecule = molecule[molecule > 0], isotopes = isotopes, :
Not compatible with STRSXP: [type=NULL].

Any input would be helpful. Thank you.

to literaly make a list of named vectors from each row of the data.frame using tidyverse you can do

my_rows <- rowwise(mydata1) |> 
           group_split() |> map(~pivot_longer(.x, 
                                    cols=everything()) |> 

I havent tested it but I'd expect you'd be able to do

map(my_rows , ~ IsoSpecify( molecule = .x , stopCondition = .9999 )

note that with purrr::map to access the .x notation, you must use ~ the tilde symbol

1 Like

You are a superb. Thank you very much.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.