我想要获取表格的数据
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
attr type
1 1 foo_and_bar
2 30 foo_and_bar_2
3 4 foo_and_bar
4 6 foo_and_bar_2
Run Code Online (Sandbox Code Playgroud)
并使用split()上面的列" type"来得到这样的东西:
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
Run Code Online (Sandbox Code Playgroud)
我提出了一些令人难以置信的复杂问题,涉及某种形式的apply工作,但我已经错了.这似乎太复杂了,不是最好的方式.我可以使用strsplit如下,但不清楚如何将其恢复到数据框中的2列.
> strsplit(as.character(before$type),'_and_')
[[1]]
[1] "foo" "bar"
[[2]]
[1] "foo" "bar_2"
[[3]]
[1] "foo" "bar"
[[4]]
[1] "foo" "bar_2"
Run Code Online (Sandbox Code Playgroud)
谢谢你的任何指示.我还没有完全理解R列表.
我试图通过从特定列中具有相同值的每组行中删除除一行之外的所有行来折叠数据框.换句话说,每组的第一行.
例如,我想转换它
> d = data.frame(x=c(1,1,2,4),y=c(10,11,12,13),z=c(20,19,18,17))
> d
x y z
1 1 10 20
2 1 11 19
3 2 12 18
4 4 13 17
Run Code Online (Sandbox Code Playgroud)
进入:
x y z
1 1 11 19
2 2 12 18
3 4 13 17
Run Code Online (Sandbox Code Playgroud)
我目前正在使用聚合来执行此操作,但是使用更多数据时性能是不可接受的:
> d.ordered = d[order(-d$y),]
> aggregate(d.ordered,by=list(key=d.ordered$x),FUN=function(x){x[1]})
Run Code Online (Sandbox Code Playgroud)
我尝试使用与此处相同的函数参数进行split/unsplit,但是unsplit抱怨重复的行号.
有可能吗?是否有一个R idiom将rle的长度向量转换为开始每次运行的行的索引,然后我可以用它来从数据帧中取出这些行?