R

时间:2017-02-24 11:36:08

标签: r dataframe

以下是一个示例数据框:

x <- list(a = c("1", "2", "2, 3"), b = c("2", "3", "5, 6"), id = c("a1", "a2", "a3"))
x1 <- as.data.frame(x)

str(x1)

'data.frame':   3 obs. of  3 variables:
$ a : Factor w/ 3 levels "1","2","2, 3": 1 2 3
$ b : Factor w/ 3 levels "2","3","5, 6": 1 2 3
$ id: Factor w/ 3 levels "a1","a2","a3": 1 2 3

x1

a     b     id
1     2     a1
2     3     a2
2, 3  5, 6  a3

你看到x1 $ a和x1 $ b在位置上有两个值:&#34; 2,3&#34;和&#34; 5,6和#34;,但在x1 $ id上只有一个值。

我的问题是,如果您知道分割这两个值的方法,请使用相同的$ id值创建一个第四个值。所以它看起来像这样:

str(x1)

'data.frame':   4 obs. of  3 variables:
$ a : Factor w/ 4 levels "1","2","2","3": 1 2 3 4
$ b : Factor w/ 4 levels "2","3","5","6": 1 2 3 4
$ id: Factor w/ 3 levels "a1","a2","a3", "a3": 1 2 3

x1

a     b     id
1     2     a1
2     3     a2
2     5     a3
3     6     a3

编辑:$ a和$ b始终具有相同数量的变量

Edit2:感谢Ronak Shah的工作

-> cSplit(x, c("a", "b"), ",", "long")

0 个答案:

没有答案