我有这个聊天对话表mydf
mydf = structure(list(User = c("Ana", "Ana", "Brian", "Ana", "Brian"), Message = c("Hi",
"How are you?", "Good. You?", "Ok", "What's up?"), Time = structure(c(1512156236.17704,
1512156238.67704, 1512156241.17704, 1512156243.67704, 1512156246.17704
), class = c("POSIXct", "POSIXt"))), .Names = c("User", "Message",
"Time"), row.names = c(NA, -5L), class = "data.frame")
#> mydf
# User Message Time
#1 Ana Hi 2017-12-01 13:23:56
#2 Ana How are you? 2017-12-01 13:23:58
#3 Brian Good. You? 2017-12-01 13:24:01
#4 Ana Ok 2017-12-01 13:24:03
#5 Brian What's up? 2017-12-01 13:24:06
我的目标是将这些数据转换为HTML格式的会话格式。我目前正在通过向数据添加标签并保存它来实现。然后我必须使用CSS进行更多工作以使其更好。 R中有更简单的方法吗?
#REMOVE REPEATING NAMES
mydf$User = with(rle(mydf$User), unlist(sapply(seq_along(values),
function(i) c(rep(values[i], 1), rep("", lengths[i] - 1)))))
#ADD TAGS
mydf$User = ifelse(mydf$User == "", "", paste0("<h2 class=\"user\">", mydf$User, "</h2>"))
mydf$Message = paste0("<h3 class=\"msg\">", mydf$Message, "</h3>")
mydf$Time = paste0("<span class=\"tm\">", mydf$Time, "</span>")
#SAVE HTML
writeLines(paste(paste(mydf$User, mydf$Message, mydf$Time), collapse = "\n"),"~/test.html")
答案 0 :(得分:0)
我不确定这是否让您满意,但我会采用扩展data.frame
并将其直接写入文件的方法
#REMOVE REPEATING NAMES
mydf$User = with(rle(mydf$User), unlist(sapply(seq_along(values),
function(i) c(rep(values[i], 1), rep("", lengths[i] - 1)))))
#SAVE HTML
write.table(
data.frame(
ifelse(mydf$User!="", "<h2 class=\"user\">",""), mydf$User, ifelse(mydf$User!="","</h2>",""),
"<h3 class=\"msg\">", mydf$Message, "</h3>",
"<span class=\"tm\">", mydf$Time, "</span>"),
file = "~/test.html", quote = F, col.names = F, row.names = F )