In my real data I got warning number of columns of result is not a multiple of vector length (arg 1)
,though my list has a unique number of cols, when I used do.call("rbind"
I want to try something else that produce the same output as do.call(rbind, list) to check whither the problem is in my list or not.
example
n = c(2, 3, 5,4)
n1 = c(2, 7, 4,6)
n2 = c(NA, NA, NA,NA)
x = list(n, n1, n2)
dat <- do.call("rbind", x)
I tried this:
df=matrix(as.numeric(unlist(x)), nrow= 3)
but
identical(dat,df)
> identical(dat,df)
[1] FALSE
PS: I do not want to change the class or str of my list
call() function in R constructs and executes a function call from a name or a function as well as a list of arguments to be passed to it. In other words, the do. call() function allows us to call the R function using a list to hold the function's arguments instead of writing out the arguments.
rbindlist is most useful when there are an unknown number of (potentially many) objects to stack, such as returned by lapply(fileNames, fread) . rbind is most useful to stack two or three objects which you know in advance. … should contain at least one data.
Just a note: Looking at
> dat
[,1] [,2] [,3] [,4]
[1,] 2 3 5 4
[2,] 2 7 4 6
[3,] NA NA NA NA
> df
[,1] [,2] [,3] [,4]
[1,] 2 4 4 NA
[2,] 3 2 6 NA
[3,] 5 7 NA NA
I am not surprised about the result that
identical(dat,df)
[1] FALSE
However, look at
df=matrix(as.numeric(unlist(x)), nrow= 3, byrow = T)
identical(dat,df)
[1] TRUE
Alternatives to do.call(rbind, list)
If you are looking for an alternative to do.call
, look at dplyr::bind_rows
(which feeds on dataframes and is quite efficient). A second alternative may be Reduce
, as in:
Reduce(rbind, x)
[,1] [,2] [,3] [,4]
init 2 3 5 4
2 7 4 6
NA NA NA NA
A further alternative is data.table::rbindlist
, which feeds on a list (!). Note though that the output will be transposed, meaning that each row will appear as one column. See
library(data.table)
rbindlist(list(x))
V1 V2 V3
1: 2 2 NA
2: 3 7 NA
3: 5 4 NA
4: 4 6 NA
You can wrap it into t()
to transpose the result, though.
More generally speaking, though, if you want to check if all elements in your list have the same length, you might be more successful in finding the error with something like
sapply(x, length)
[1] 4 4 4
or depending on how your actual data looks like, a variation such as ncol
or so instead of length
. If the list elements have column names, then names
might be a valid alternative as well.
You need to add byrow = TRUE
:
df=matrix(as.numeric(unlist(x)), nrow= 3, byrow = TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With