2016-09-23 35 views
-3

我有一个向量作为下文陈述:转换的矢量数据帧具有多个列

("#99" "Hershey" "$6.7 B" "7%" "$4.7 B" "$562 M" "Consumer Packaged Goods" 
"#100" "Costco" "$6.7 B" "14%" "$117.3 B" "-" "Retail") 

对于我所提到的只是出于700个元件的几个要素的简单性。

我想将它转换为如下数据帧:

S.NO Brand Brandval Change Revenue Cost Industry 
99 Hershey $6.7 B 7%  $4.7 B $562M Consumer Packaged goods 
100 Costco $6.7B  14% $117.3B -  Retail 

我试图as.data.frame,但它给了我一个单列的结果,而我想将它拆分成7列,解释以上。 请帮忙。

+0

as.datafram(DF)这里df是乌尔数据 –

+0

如果我申请as.data.frame在矢量上,它给了我一个单独的列。 – assasinC

+4

'as.data.frame(矩阵(vec,ncol = 7,byrow = T))','vec'是你的向量。 – mtoto

回答

1

您可以这样做:根据重复的1:7的矢量分割您的矢量,然后应用cbind.data.frame。最后,加列名

x=c("#99", "Hershey", "$6.7 B", "7%", "$4.7 B", "$562 M", "Consumer Packaged Goods", "#100", "Costco", "$6.7 B", "14%", "$117.3 B", "-", "Retail") 
res <- cbind.data.frame(split(x, rep(1:7, times=length(x)/7)), stringsAsFactors=F) 
names(res) <- c("S.NO", "Brand", "Brandval", "Change", "Revenue", "Cost", "Industry") 
str(res) 
#### 'data.frame': 2 obs. of 7 variables: 
#### $ S.NO : chr "#99" "#100" 
#### $ Brand : chr "Hershey" "Costco" 
#### ... 

您可以选择的选项StringAsFactors,让你得到任何字符或因素列

+1

@mtoto在上面的注释中提供的解决方案也可以工作。谢谢。 – assasinC

相关问题