简体   繁体   中英

Reshape 4 variables at once R

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.

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

data

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM