在一个列表列表中转换多个向量

时间:2018-07-10 21:41:43

标签: r list vector

我正在寻找一种将多个相同长度的向量转换为命名列表的方法。

例如,如果我有矢量:

v1 <- c("a", "b", "c")
v2 <- c("x", "y", "z")

,列表应为:

list(
  list(
    name = "a",
    value = "x"
  ),
  list(
    name = "b",
    value = "y"
  )
  list(
    name = "c",
    value = "z"
  )
)

当您为一个请求中包含多条记录的API生成请求正文时,这很有用。

2 个答案:

答案 0 :(得分:3)

这应该有效:

l <- mapply(
  function(name, value) list(name = name, value = value),
  v1, v2,
  USE.NAMES = FALSE, 
  SIMPLIFY = FALSE
)
str(l)

# List of 3
# $ :List of 2
#  ..$ name : chr "a"
#  ..$ value: chr "x"
# $ :List of 2
#  ..$ name : chr "b"
# ..$ value: chr "y"
# $ :List of 2
#  ..$ name : chr "c"
#  ..$ value: chr "z"

答案 1 :(得分:2)

另一个选择是Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ''When i click the button If CantidadVer1.Text = 0 Then ''this verifies how many Labels i have created CantidadVer1.Text = +1 ''this updates the verification Dim lbl1 As New Label ''this creates the labels lbl1.Size = New System.Drawing.Size(159, 23) lbl1.Text = (Product.Text) ''product.text is a TextBox lbl1.Location = New System.Drawing.Point(12, 80 + 20) '' i add 20 more everytime i create a label Me.Controls.Add(lbl1) ElseIf CantidadVer1.Text = 2 Then ''at this point it creates the label but "crashes" (It dosent work anymore) CantidadVer1.Text = +1 Dim lbl2 As New Label lbl2.Size = New System.Drawing.Size(159, 23) lbl2.Text = (Product.Text) lbl2.Location = New System.Drawing.Point(12, 80 + 40) Me.Controls.Add(lbl2) ElseIf CantidadVer1.Text = 2 Then CantidadVer1.Text = +1 Dim lbl3 As New Label lbl3.Size = New System.Drawing.Size(159, 23) lbl3.Text = (Product.Text) lbl3.Location = New System.Drawing.Point(12, 80 + 60) Me.Controls.Add(lbl3) ElseIf CantidadVer1.Text = 3 Then CantidadVer1.Text = +1 Dim lbl4 As New Label lbl4.Size = New System.Drawing.Size(159, 23) lbl4.Text = (Product.Text) lbl4.Location = New System.Drawing.Point(12, 80 + 80) Me.Controls.Add(lbl4) ElseIf CantidadVer1.Text = 4 Then CantidadVer1.Text = +1 Dim lbl4 As New Label lbl4.Size = New System.Drawing.Size(159, 23) lbl4.Text = (Product.Text) lbl4.Location = New System.Drawing.Point(12, 80 + 100) Me.Controls.Add(lbl4) End If End Sub 中的pmap

purrr