Home > Mobile >  Transforming dataframe into some format
Transforming dataframe into some format

Time:02-13

I have multiple csv. files in the following format

when opening as csv. enter image description here

imported into R enter image description here

I would like to transform the dataframe into the following format enter image description here

CodePudding user response:

Its ideal to also share some dummy data so that its easier for us to respond.

tidyr option using separate_rows()

library(dplyr)
df %>% 
  tidyr::separate_rows(tenant_id,sep=" ") # assuming the separator is a space

CodePudding user response:

Well, it would be nice if you can use the data, but you can use something like that.

library(stringr)
df = data.frame(property_type = c(1,2,3),
                tenant_id = c('1 1 1 1 1', '2 2 2 2', '3 3 3'))

df = data.frame(do.call(rbind, with(
  df, mapply(\(p, t) cbind(p, str_split(t, ' ')[[1]]), property_type, tenant_id)
)))
colnames(df) = c('property_type', 'tenant_id')
df
  •  Tags:  
  • r
  • Related