简体   繁体   English

转换数据框元素中的列表元素

[英]Transform elements of list in elements of a data frame

I have these data:我有这些数据:

a <- data.frame(element1 = c("JB", "AC", "DO", "MR"),
                element2 = c(1, 3, 4, 2))
b <- list(JB = c("a", "b", "s"), DO = c("ER", "TR", "OP"))

I want to create a new data frame ab similar to data frame a , but such that the elements of the first column are the elements of the list b.我想创建一个新的数据帧ab类似于数据帧a ,而使得第一列的元素列表B的元素。 Ie in the new ab data frame, the elements of the first column that have the same title as the elements of the list b take the value of the elements in the list b .即,在新的ab数据帧中,具有的标题列表B的元件相同的第一列中的元素采取在列表中的元素的值b

EDIT : The output should be the same as a, but with element1 elements being lists:编辑:输出应该与 a 相同,但 element1 元素是列表:

> ab
  element1 element2
1       JB        1
2       AC        3
3       DO        4
4       MR        2
a <- data.frame(element1 = c("JB", "AC", "DO", "MR"),
            element2 = c(1, 3, 4, 2))

b <- data.frame(JB = c("a", "b", "s"), DO = c("ER", "TR", "OP"))

merge(b,a)

This should do the job.这应该可以完成工作。 Output will be:输出将是:

   JB DO element1 element2
1   a ER       JB        1
2   b TR       JB        1
3   s OP       JB        1
4   a ER       AC        3
5   b TR       AC        3
6   s OP       AC        3
7   a ER       DO        4
8   b TR       DO        4
9   s OP       DO        4
10  a ER       MR        2
11  b TR       MR        2
12  s OP       MR        2

Isn't that just那不只是

ab <- within(a, element1 <- b[element1])

Output输出

> str(ab)
'data.frame':   4 obs. of  2 variables:
 $ element1:List of 4
  ..$ JB: chr  "a" "b" "s"
  ..$ NA: NULL
  ..$ DO: chr  "ER" "TR" "OP"
  ..$ NA: NULL
 $ element2: num  1 3 4 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM