我有一个数据集:
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变量解释了每个变量中可用的所有类别(在variableName中列出。我现在正在尝试生成一个总结它的文本文件:
理想输出将是包含以下内容的文本文件:
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"
我是R的初学者,所以任何帮助都会非常感激!
答案 0 :(得分:5)
根据显示的预期输出,您可以使用dQuote
(在评论中使用与@David Arenburg代码类似的语法)
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”"
或使用dplyr
library(dplyr)
df %>%
group_by(variableName) %>%
summarise(V1= paste(order, dQuote(categoryName), collapse= ' ')) %>%
transmute(V1= paste(variableName, V1, sep=": "))
答案 1 :(得分:1)
Akrun的data.table解决方案后续行动的另一个选择
<div id="profile2">
<img height="180px" width="180px" src="http://#/files/theme/nat2.jpg">
<a href="http://www.fightingfitlondon.co.uk/nat-roberson.html">Nat Roberson</a>
<input id="main2" type="radio" name="menu" checked>
<label for="main"></label>
<input id="mail2" type="radio" name="menu">
<label for="mail"></label>
<input id="menu2" type="radio" name="menu">
<label for="menu"></label>
<div id="menu-content2">
<span id="info2">About:<br/><br/>Nat joined All Stars Boxing Gym in London when he was 9 years old. He had his first bout at 11 and boxed competitively for 8 years until he was 19.</span>
<span id="contacts2">
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
</span>
<span id="more2">
<a href="#/nat-roberson.html">Profile</a>
<a href="">Timetables</a>
<a href="">Activities</a>
<a href="">Speciality</a>
</span>
</div>