Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:是否有内置的功能来排序列表?_R_List - Fatal编程技术网

R:是否有内置的功能来排序列表?

R:是否有内置的功能来排序列表?,r,list,R,List,在R中,我生成了以下列表L: >L [[1]] [1] "A" "B" "C" [[2]] [1] "D" [[3]] [1] NULL 我想操纵列表L到达数据库df类似 >df df[,1] df[,2] "A" 1 "B" 1 "C" 1 "D" 2 其中第2列给出了第1列中相应元素在列表L中的位置。 我的问题是:是否有一个()内置的R函数可以快速执行此操作

在R中,我生成了以下列表
L

>L
[[1]]
[1] "A" "B" "C"  

[[2]]
[1] "D"  

[[3]]
[1] NULL
我想操纵列表
L
到达数据库
df
类似

>df
    df[,1] df[,2]
       "A"      1 
       "B"      1
       "C"      1 
       "D"      2
其中第2列给出了第1列中相应元素在列表
L
中的位置。 我的问题是:是否有一个()内置的R函数可以快速执行此操作?我可以使用“蛮力”,但是当我考虑更大的列表时,我的解决方案不能很好地扩展。


谢谢大家

由于您的
NULL
值,您将得到一个
警告
,但如果您提供列表项
名称
,则可以使用
堆栈

L <- list(c("A", "B", "C"), "D", NULL)
stack(setNames(L, seq_along(L)))
#   values ind
# 1      A   1
# 2      B   1
# 3      C   1
# 4      D   2
# Warning message:
# In stack.default(setNames(L, seq_along(L))) :
#   non-vector elements will be ignored
类似地,如果已经去掉了
NULL
列表元素,则可以使用“重塑2”中的
melt
。你不会从简洁中得到任何好处,我也不确定你会从效率中得到任何好处,但我想我会把它作为一种选择来分享

library(reshape2)
names(L) <- seq_along(L)
melt(L[!sapply(L, is.null)])
library(重塑2)

名称(L)由于您的
NULL
值,您将得到一个
警告
,但如果您提供列表项
名称
,则可以使用
堆栈

L <- list(c("A", "B", "C"), "D", NULL)
stack(setNames(L, seq_along(L)))
#   values ind
# 1      A   1
# 2      B   1
# 3      C   1
# 4      D   2
# Warning message:
# In stack.default(setNames(L, seq_along(L))) :
#   non-vector elements will be ignored
类似地,如果已经去掉了
NULL
列表元素,则可以使用“重塑2”中的
melt
。你不会从简洁中得到任何好处,我也不确定你会从效率中得到任何好处,但我想我会把它作为一种选择来分享

library(reshape2)
names(L) <- seq_along(L)
melt(L[!sapply(L, is.null)])
library(重塑2)

names(L)Ananda的答案似乎比这个好,但我还是要说出来:

> cbind(unlist(L), rep(1:length(L), sapply(L, length)))
     [,1] [,2]
[1,] "A"  "1" 
[2,] "B"  "1" 
[3,] "C"  "1" 
[4,] "D"  "2"

阿南达的回答似乎比这个好,但我还是要说:

> cbind(unlist(L), rep(1:length(L), sapply(L, length)))
     [,1] [,2]
[1,] "A"  "1" 
[2,] "B"  "1" 
[3,] "C"  "1" 
[4,] "D"  "2"

stack
完成任务;非常感谢你!我不知道:-)
stack
做这个工作;非常感谢你!我不知道:-)谢谢托马斯的回答;谢谢你的回答;谢谢。