本文介绍了将列转换为 r 中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用代码形成了以下数据
I have the below data formed using code
test <- data.frame(dis = c(10,20,30,40),dur=c(30,40,60,90),method=c("car","car","Bicycle","Bicycle"),to_lon=c(-1.980,-1.5678,-1.324,-1.456),to_lat=c(55.3009,55.3416,55.1123,55.2234),from_lon=c(-1.4565,-1.3424,-1.4566,-1.1111),from_lat=c(76.8888,65.8999,76.9088,25.3344))
dis dur method to_lon to_lat from_lon from_lat
1 10 30 car -1.9800 55.3009 -1.4565 76.8888
2 20 40 car -1.5678 55.3416 -1.3424 65.8999
3 30 60 Bicycle -1.3240 55.1123 -1.4566 76.9088
4 40 90 Bicycle -1.4560 55.2234 -1.1111 25.3344
我想转换此数据框,使其在一行中包含 to_lat 和 to_lon,在下一行中包含 from_lat 和 from_lon.其余的细节不需要改变,可以复制.想要的结果应该如下
I want to convert this data frame such that it has one row for to_lat and to_lon and in the next row it has from_lat and from_lon. The rest of the details do not need to change and can be replicated. The desired result should be as below
dis dur method longitude latitude
from 10 30 car -1.98 55.3009
to 10 30 car -1.4565 76.8888
from 20 40 car -1.5678 55.3416
to 20 40 car -1.3424 65.8999
from 30 60 Bicycle -1.324 55.1123
to 30 60 Bicycle -1.4566 76.9088
from 40 90 Bicycle -1.456 55.2234
to 40 90 Bicycle -1.1111 25.3344
任何帮助将不胜感激.
谢谢.
推荐答案
我们可以使用data.table
中的melt
,它可以采取多个measure
> 列.
We can use melt
from data.table
which can take multiple measure
columns.
library(data.table)
dM <- melt(setDT(test), measure=patterns('lon', 'lat'),
value.name=c('longitude', 'latitude'))
#change the 'variable' column from numeric index to 'from/to'
dM[, variable:= c('from', 'to')[variable]]
#create a sequence column grouped by 'variable'
dM[,i1:= 1:.N ,variable]
#order based on the 'i1'
res <- dM[order(i1)][,i1:=NULL]
res
# dis dur method variable longitude latitude
#1: 10 30 car from -1.9800 55.3009
#2: 10 30 car to -1.4565 76.8888
#3: 20 40 car from -1.5678 55.3416
#4: 20 40 car to -1.3424 65.8999
#5: 30 60 Bicycle from -1.3240 55.1123
#6: 30 60 Bicycle to -1.4566 76.9088
#7: 40 90 Bicycle from -1.4560 55.2234
#8: 40 90 Bicycle to -1.1111 25.3344
这篇关于将列转换为 r 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!