简体   繁体   中英

Convert list of dataframes to list of numeric vectors in R

I have a list L of dataframes. The elements (dataframes) of L are unnamed. Each element includes only one variable Var (same for all elements) and one observation (unique across elements). The observations are lists of random "numbers". An elements of L can look like: :'data.frame': 1 obs. of 1 variable: $ Var: chr "\\"4\\", \\"32\\", \\"25\\", \\"4\\", " :'data.frame': 1 obs. of 1 variable: $ Var: chr "\\"4\\", \\"32\\", \\"25\\", \\"4\\", " . And is.atomic(L[[1]]$Var) returns TRUE . I am looking for a way to convert L into a list of unnamed numeric vectors. End result should be:

> L
[[1]]
[1]  4 32  25 4

Right now I have:

> L
[[1]]
                   Var
1 "4", "32", "25", "4",

I have tried as.numeric but keep getting the warning NAs introduced by coercion and the result is not as expected. Obviously I am doing something wrong. Any help is appreciated!

edit: deleted the L sample as it was unnecessary.

Your strings need separating and stripping of quotation marks, by the look of it. They might also be factors. Try something like this...

L <- list(data.frame(Var='"1","2","3","4"'),data.frame(Var='"3","4","5","6"'))

K <- lapply(L,function(df) as.numeric(gsub('"','',unlist(strsplit(as.character(df[1,1]),',')))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM