user2963882 user2963882 - 1 month ago 17
R Question

List to specific dataframe

I want to create a dataframe from a list. The list is from a shiny handsontable input

When I call the input I got:

unlist(input$hot$data)

texta
2 80%
3 100%
4 100%
5 100%
6 textb
7 100%
8 100%
9 100%
10 100%
11 textc
12 80%
13 100%
14 100%
15 100%
16 textd
17 5%
18 95%
19 100%
20 35%


What I am trying to is to get a df like:

col1 col2 col3 col4 col5
texta 80 100 100 100
textb 100 100 100 100
textc 80 100 100 100
textd 5 95 100 35


data



# output dput(input$hot$data)
list(list("texta", "80%", "100%", "100%", "100%"), list(
"textb", "100%", "100%", "100%", "100%"), list(
"textc", "80%", "100%", "100%", "100%"), list("textd",
"5%", "95%", "100%", "35%"))

Answer
data <- list(list("texta", "80%", "100%", "100%", "100%"), list(
    "textb", "100%", "100%", "100%", "100%"), list(
    "textc", "80%", "100%", "100%", "100%"), list("textd", 
    "5%", "95%", "100%", "35%"))

data <- data.frame(t(sapply(data, unlist)))

If don't want X1, X2, ... as your column names then add:

colnames(data) <- paste0("col", 1:ncol(data))
data

Then data is the following data.frame:

    col1 col2 col3 col4 col5
 1 texta  80% 100% 100% 100%
 2 textb 100% 100% 100% 100%
 3 textc  80% 100% 100% 100%
 4 textd   5%  95% 100%  35%

If you want to remove % symbol and covert your numeric values to numbers then:

data[,-1] <- sapply(data[,-1], function(x) as.numeric(sub("%", "", x)))