我有一个像这样的data.frame:
x <- data.frame(names=c('NG_1', 'NG_2', 'FG_1', 'FG_2'), score=c(1,2,3,4), label=c('N','N','F','F'))
x
names score label
1 NG_1 1 N
2 NG_2 2 N
3 FG_1 3 F
4 FG_2 4 F
我想通过子串匹配对两组(N,F)进行分组。例如,NG_1
与FG_1
匹配。我正在寻找我的结果:
y <- data.frame(name1=c('NG_1','NG_2'), name2=c('FG_1', 'FG_2'), score1=c(1,2), score2=c(3,4))
y
name1 name2 score1 score2
1 NG_1 FG_1 1 3
2 NG_2 FG_2 2 4
结果表不需要看起来像上面那样,但我确实希望将分数分组。
我能想到的唯一方法是在标签= N
的所有行上运行for循环,并将每个行匹配到F
。还有什么更好的吗?
答案 0 :(得分:1)
我们可以使用data.table
执行此操作。转换&#39; data.frame&#39;到&#39; data.table&#39; (setDT(x)
),根据&#39;标签&#39;创建分组变量(&#34; Grp&#34;)和序列(&#34; N&#34;),然后使用{{ 1}}(可以使用多个dcast
列)来转换&#39; long&#39;广泛的&#39;格式。
value.var
答案 1 :(得分:0)
这是使用dplyr / tidyr
的方法> require(dplyr)
> require(tidyr)
> x <- data.frame(names=c('NG_1', 'NG_2', 'FG_1', 'FG_2')
+ , score=c(1,2,3,4)
+ , label=c('N','N','F','F')
+ , stringsAsFactors = FALSE
+ )
> x
names score label
1 NG_1 1 N
2 NG_2 2 N
3 FG_1 3 F
4 FG_2 4 F
> # create new 'label' for grouping
> x$label <- substring(x$names, 4, 4) # extract grouping criteria
> x %>%
+ gather(key, value, -label) %>% # wide to long using 'label'
+ group_by(label, key) %>% # group for adding newkey
+ mutate(newkey = paste(key , seq(length(key)), sep = "_")) %>%
+ ungroup %>% # remove grouping criteria
+ select(-key) %>% # remove the 'key' column -- not needed
+ spread(newkey, value) %>% # long to wide
+ select(-label) # remove the 'label' column -- not needed
Source: local data frame [2 x 4]
names_1 names_2 score_1 score_2
(chr) (chr) (chr) (chr)
1 NG_1 FG_1 1 3
2 NG_2 FG_2 2 4