assasinC assasinC - 2 months ago 7
R Question

Convert a vector to data frame with multiple columns

I have a vector as stated below:

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


For simplicity i have mentioned only few elements out of 700 elements.

I want to convert it to data frame as below:

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


I was trying as.data.frame but it gives me results in one single column while I want to split it into 7 columns as explained above.
Please help.

Answer

You can do like this: split your vector according to a vector of repeated 1:7, then apply cbind.data.frame. Eventuelly, add column names

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"
#### ...

You can choose the option StringAsFactors so that you get either character or factor columns