Reputation: 63
I have a dataset that separates a WORKER_ID's HOME_ID and WORK_ID based on latitude and longitude, but all in the same row. I would like to reshape long so that the HOME_ID and WORK_ID are in the same column, as well as the other variables. An example of data is below:
WORKER_ID WORK_ID HOME_ID LAT_WORK LONG_WORK LAT_HOME LONG_HOME
32435353 23434343 32435353 39.54 41.53 39.64 42.43
I would like it to look like this:
WORKER_ID ID LAT LONG
32435353 23434343 39.54 41.53
32435353 32435353 39.64 42.43
I am getting a bunch of error messages when I try reshape, and was wondering if anyone would know the correct syntax. Thank you in advance.
Upvotes: 0
Views: 41
Reputation: 1771
You can use the function gather
from tidyr or the function melt
from data.table just like akrun said.
Also akrun data.table's code is definitively working when I reproduce your example OP.
Upvotes: 0
Reputation: 887118
We can use melt
from data.table
library(data.table)
melt(setDT(df1), measure = patterns("(WORK|HOME)_ID", "LAT", "LONG"),
value.name = c("ID", "LAT", "LONG"))[, variable := NULL][]
# WORKER_ID ID LAT LONG
#1: 32435353 23434343 39.54 41.53
#2: 32435353 32435353 39.64 42.43
df1 <- structure(list(WORKER_ID = 32435353L, WORK_ID = 23434343L,
HOME_ID = 32435353L,
LAT_WORK = 39.54, LONG_WORK = 41.53, LAT_HOME = 39.64,
LONG_HOME = 42.43), class = "data.frame", row.names = c(NA,
-1L))
Upvotes: 1