R 将向量聚合到数据帧中
我想把一个向量转换成一个数据帧。该向量由一个唯一的ID组成,后面跟着其他字段。字段是详尽的,大约30个不同的字段,都用反斜杠标记R 将向量聚合到数据帧中,r,aggregate,R,Aggregate,我想把一个向量转换成一个数据帧。该向量由一个唯一的ID组成,后面跟着其他字段。字段是详尽的,大约30个不同的字段,都用反斜杠标记 \ID a \description text yes \definition text yes \other.info text yes \ID b \definition text yes \other.info text yes \ID d \description text yes \other.info text yes \transla
\ID a
\description text yes
\definition text yes
\other.info text yes
\ID b
\definition text yes
\other.info text yes
\ID d
\description text yes
\other.info text yes
\translation text yes
我需要将其转换为:
ID description definition other.info translation
a text yes text yes text yes
b text yes text yes
d text yes text yes text yes
谢谢你的帮助这里有一些快速而肮脏的东西,但却能完成工作:
library(stringr) # Will use str_extract() with some regex
library(magrittr) # pipes: %>%
library(data.table) # rbindlist (I think dplyr has bind_rows() which is similar)
split(vect, cumsum(grepl("ID", vect))) %>%
lapply(function(x) setNames(data.frame(t(str_extract(x, "\\w+$"))), str_extract(x, "^.+\\s")) ) %>%
rbindlist(fill = TRUE) %>%
setNames(gsub("text|\\\\", "", names(.)))
ID description definition other.info translation
1: a yes yes yes <NA>
2: b <NA> yes yes <NA>
3: d yes <NA> yes yes
library(stringr)#将str_extract()与一些正则表达式一起使用
库(magrittr)#管道:%%>%
library(data.table)#rbindlist(我认为dplyr有类似的bind_rows())
拆分(vect,cumsum(grepl(“ID”,vect))%>%
lappy(函数(x)集合名(data.frame(t(str_extract(x,\\w+$)),str_extract(x,“^.+\\s”))%%>%
rbindlist(fill=TRUE)%>%
集合名称(gsub(“文本”;\ \ \ \“,”,名称())
ID描述定义其他.info翻译
1:a是的,是的
b是的
3:d是的,是的
数据:
vect非常感谢您……虽然我的RStudio在执行时崩溃了,但它似乎起到了作用:)
vect <- c("\\ID a", "\\description text yes", "\\definition text yes", "\\other.info text yes",
"\\ID b", "\\definition text yes", "\\other.info text yes", "\\ID d",
"\\description text yes", "\\other.info text yes", "\\translation text yes"
)