简体   繁体   中英

R: apply as.list to data frame converts numeric to character

When trying to convert data frame to a list resembling a nested dictionary I tried using a following command:

 df = data.frame(col1 = c('a', 'b'), col2 = c(1, 2))
 df[,1] = as.character(df[,1])

 ls1 = apply(df, 1, as.list)
 print(ls1)

However, the values of col2 in ls1 now seem to be converted to character:

 class(ls1[[2]]$col2)
 # [1] "character"

This workaround works, but I am curious if somebody knows, why the result is not the same as in previous code?

 ls2 = as.list(df[1,])
 for(i in 2:nrow(df)){
   ls2 = list(ls2, as.list(df[i,]))
 }
 print(ls2)

 class(ls1[[2]]$col2)
 # [1] "numeric"

Instead of apply , which converts the data to matrix and matrix can have only single class, use split

lst1 <- unname(split(df, seq_len(nrow(df))))

If we need a JSON output, the dataset can be directly converted to JSON with toJSON

jsonlite::toJSON(df)
#[{"col1":"a","col2":1},{"col1":"b","col2":2}] 

Based on the conversation with OP, dataset is passed as a named list that needs to be converted to JSON format

toJSON(list(listName = df))
#{"listName":[{"col1":"a","col2":1},{"col1":"b","col2":2}]} 

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