Reputation: 659
I have a dataset:
variableName<-c("Mood","Mood","Mood","HappinessIndex","HappinessIndex","HappinessIndex","HappinessIndex","weather","weather","weather","weather","weather")
order<-c(1,2,3,1,2,3,4,1,2,3,4,5)
categoryName<-c("Happy","Normal","Sad","Very Happy","Happy","Unhappy","Sad","Sunny","Cloudy","Windy","Rainy","Stormy")
df<-data.frame(variableName,order,categoryName)
categoryName variable explains all the categories available in each variable (which is listed in variableName. I am now trying to produce a text file that would summarise that:
the ideal output would be a text file containing the following:
Mood: 1 "Happy" 2 "Normal" 3 "Sad"
Happiness Index: 1 "Very Happy" 2 "Happy" 3 "Unhappy" 4 "Sad"
weather: 1 "Sunny" 2 "Cloudy" 3 "Windy" 4 "Rainy" 5 "Stormy"
I am beginner user of R so any help would be much appreciated!
Upvotes: 2
Views: 1374
Reputation: 4472
Another option in follow-up to Akrun's data.table solution
do.call(paste,
c(setDT(df)[, list(variable=paste(order, dQuote(categoryName),
collapse=' ')), by=variableName], sep = ": "))
#[1] "Mood: 1 “Happy” 2 “Normal” 3 “Sad”"
#[2] "HappinessIndex: 1 “Very Happy” 2 “Happy” 3 “Unhappy” 4 “Sad”"
#[3] "weather: 1 “Sunny” 2 “Cloudy” 3 “Windy” 4 “Rainy” 5 “Stormy”"
Upvotes: 1
Reputation: 887158
Based on the expected output showed, you may use dQuote
(Using similar syntax as @David Arenburg's code in the comments)
library(data.table)
setDT(df)[,paste(order, dQuote(categoryName), collapse=' '), by = variableName][,
paste(variableName, V1, sep=": ")]
#[1] "Mood: 1 “Happy” 2 “Normal” 3 “Sad”"
#[2] "HappinessIndex: 1 “Very Happy” 2 “Happy” 3 “Unhappy” 4 “Sad”"
#[3] "weather: 1 “Sunny” 2 “Cloudy” 3 “Windy” 4 “Rainy” 5 “Stormy”"
Or using dplyr
library(dplyr)
df %>%
group_by(variableName) %>%
summarise(V1= paste(order, dQuote(categoryName), collapse= ' ')) %>%
transmute(V1= paste(variableName, V1, sep=": "))
Upvotes: 5