1

I would like to transform values from a dataset to a list as numeric values.

Here is a sample dataset:

df <- data.frame(
  a = c(5.5, 6, 7),
  b = c(1.1, 2.5, 3.5))

# convert dataframe to list
df.list <- split(df, seq(nrow(df)))

enter image description here

The list looks like the above in the R environment. My desired output in the R environment is like below by getting rid of the $s, as, and bs.

enter image description here

I tried this below but it did not really give what I wanted.

for (i in 1:length(df.list)) {
  df.list[[i]] <- lapply(df.list[[i]], function(x) as.numeric(as.character(df.list[[i]])))
  
}

enter image description here

Does ANyone have any ideas?

Thanks!

1 Answer 1

1

We can use asplit from base R. Specify the MARGIN as 1 for rows and 2 for column wise split

out <- lapply(asplit(unname(df), 1), as.vector)
str(out)
#List of 3
#$ : num [1:2] 5.5 1.1
#$ : num [1:2] 6 2.5
#$ : num [1:2] 7 3.5

Or another option is apply

out2 <- do.call(c, apply(unname(df), 1, list)) 
identical(out, out2)
#[1] TRUE

From the OP's split, we can unlist the list elements

out3 <- lapply(unname(df.list), unlist, use.names = FALSE)
identical(out, out3)
#[1] TRUE
Sign up to request clarification or add additional context in comments.

1 Comment

appreciated your quick turnaround. Great solutions. I picked the first one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.