R:对表2中的行进行排序
我有一种情况,我需要使用R中的重塑2包来融化数据R:对表2中的行进行排序,r,reshape2,melt,R,Reshape2,Melt,我有一种情况,我需要使用R中的重塑2包来融化数据 melt(head(faithful), measure.vars = names(faithful)) 这将提供以下输出: variable value 1 eruptions 3.600 2 eruptions 1.800 ... 7 waiting 79.000 8 waiting 54.000 ... 我想根据dataframe中的列来排列输出的前几行。例如: variable value 1
melt(head(faithful), measure.vars = names(faithful))
这将提供以下输出:
variable value
1 eruptions 3.600
2 eruptions 1.800
...
7 waiting 79.000
8 waiting 54.000
...
我想根据dataframe中的列来排列输出的前几行。例如:
variable value
1 eruptions 3.600
2 waiting 79.000
3 eruptions 1.800
4 waiting 54.000
...
如何通过避免循环来实现这一点。我将使用额外的列
标记
df<-faithful
df<-cbind(df,tag=1:nrow(faithful))
df2<-melt(df,id.vars = "tag")
df2<-df2[order(df2$tag),]
df2$tag<-NULL#drop it like it's hot
head(df2)
我知道需要一个reformae2
解决方案,但另一个好方法是使用tidyverse
library(tidyverse)
head(faithful) %>% mutate(tag = 1:n()) %>% gather(var, val, -tag) %>% arrange(tag)
tag var val
1 1 eruptions 3.600
2 1 waiting 79.000
3 2 eruptions 1.800
4 2 waiting 54.000
# etc
不需要中间对象。我认为OP应该保留标签。如果他们如此关心排序,他们至少应该保留一些方法,呃,试图模仿OP的输出:)这就是“下降”的原因。
library(tidyverse)
head(faithful) %>% mutate(tag = 1:n()) %>% gather(var, val, -tag) %>% arrange(tag)
tag var val
1 1 eruptions 3.600
2 1 waiting 79.000
3 2 eruptions 1.800
4 2 waiting 54.000
# etc