将矢量转换为具有多列的数据帧

时间:2016-09-23 07:48:36

标签: r dataframe

我有一个如下所述的矢量:

("#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列,如上所述。 请帮忙。

1 个答案:

答案 0 :(得分:3)

您可以这样做:根据重复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选项,以便获得字符或系数列