0
如果我想以下data.frame轉換:如何在數據框上執行聚合命令的反轉?
>M
name ID
a 1
b,c 2
d,e 3
f 4
這一個:
>M
name ID
a 1
b 2
c 2
d 3
e 3
f 4
我如何能做到這一點的轉換爲第一列的所有元素?
由於
如果我想以下data.frame轉換:如何在數據框上執行聚合命令的反轉?
>M
name ID
a 1
b,c 2
d,e 3
f 4
這一個:
>M
name ID
a 1
b 2
c 2
d 3
e 3
f 4
我如何能做到這一點的轉換爲第一列的所有元素?
由於
這裏是一個基礎R溶液:
# split the names into a list
nameList <- strsplit(df$name, split=",")
# get your new data.frame
newdf <- data.frame(names=unlist(nameList), ID=rep(df$ID, sapply(nameList, length)))
這使用rep
重複ID相同數量的倍名稱變量已被拆分。這意味着,如果你有3個或更多的名字,它也可以工作。
數據
df <- read.table(header=T, text="name ID
a 1
b,c 2
d,e 3
f 4", stringsAsFactors=F)
輸出
> newdf
names ID
1 a 1
2 b 2
3 c 2
4 d 3
5 e 3
6 f 4
可以使用unnest()
從tidyr
:
library(dplyr); library(tidyr)
mutate(M, name = strsplit(name, ",")) %>% unnest(name)
Source: local data frame [6 x 2]
ID name
(chr) (chr)
1 1 a
2 2 b
3 2 c
4 3 d
5 3 e
6 4 f
[酮](http://stackoverflow.com/questions/29758504/split-data-frame-row-into-multiple -rows-based-commas),[two](http://stackoverflow.com/questions/37492809/add-new-line-in-df-using-grep-or-regex),[three](http ://stackoverflow.com/questions/30525811/how-to-separate-comma-separated-values-in-r-in-a-new-row),[four](http://stackoverflow.com/questions/33113263/splitting-a-single-column-into-multiple-observation-using-r),[five](http://stackoverflow.com/questions/33571978/split-value-from-a-data-框架和創建-附加行到商店其組分) – rawr