我在文件中有一组字符串,如下所示:
我需要将这些字符串转换为数据框架,其中上面列表中的每个惟一单词都会变成列名。有什么建议吗?
发布于 2014-08-01 09:43:48
假设你的字符串是在一个向量中组织的,并且你实际上想为每个唯一的单词建立一个列,你可以这样做。
strVec <- c("SONY BRAVIA TV32 T550","SONY BRAVIA TV40 S530","SONY BRAVIA TV40 S530","SONY BRAVIA TV42 S530A")
words <- sapply(strVec,FUN=function(x) strsplit(x," ")) #split strings at " "
uniqueWords <- unique(unlist(words)) # get the unique words
mydf <- data.frame(matrix(nrow=0,ncol=length(uniqueWords))) # create new df
colnames(mydf) <- uniqueWords # give it the right colnames发布于 2014-08-01 14:08:32
不完全确定你想要什么。此外,您还有SOINY和SONY,TV和number之间的空格。希望您的实际数据集中不是这种情况。
Lines <- readLines(n=20)
SAMSUNG LCD TV40 B450
SMALL 14 INCH WEGASONIC TVS
SONY LCD TV22 T400A
SONY BRAVIA TV32 T550
SONY BRAVIA TV40 S530
SONY BRAVIA TV40 S530
SONY BRAVIA TV42 S530A
SONY BRVIA TV32 S550A
SONY LCD TV19 T400A
SONY LCD TV22 BX300
SONY LCD TV22 T400A
SONY LCD TV22 T400A
SONY LCD TV22 T550
SONY LCD TV26 BX300
SONY LCD TV32 BX300
SONY LCD TVV19 BX300
STAR TV 21 MODEL 2103P
TELESTAR 14 1486 COLOUR TV
TELESTAR TV 14 1486
TELESTAR TV 14 1486
library(stringr)
Lines <- str_trim(Lines) #removes trailing and leading spaces
Un <- unique(scan(text=Lines, what="")) #extractunique words
res <- sapply(Un, function(.pat) grepl(.pat, Lines)) +0
res[1:3,1:3]
# SAMSUNG LCD TV40
#[1,] 1 1 1
#[2,] 0 0 0
#[3,] 0 1 0
as.data.frame(res) #converts to dataframe.https://stackoverflow.com/questions/25076508
复制相似问题