I have this df:
df = data.frame(Meaning = c('Tax', 'Internet', 'Tax', 'Phone', 'Tax', 'Car'),
Code = c(4656, 6152, 4656, 6150, 4656, 6151),
Total = c(0.73, 4.4, 1.33, 8, 1.67, 10),
Tax = c(0.73, NA, 1.33, NA, 1.67, NA),
Subtotal = c(NA, 3.67, NA, 6.67, NA, 8.33),
stringsAsFactors = FALSE)
> df
Meaning Code Total Tax Subtotal
Tax 4656 0.73 0.73 NA
Internet 6152 4.40 NA 3.67
Tax 4656 1.33 1.33 NA
Phone 6150 8.00 NA 6.67
Tax 4656 1.67 1.67 NA
Car 6151 10.00 NA 8.33
And I would like to use reshape() or stack to obtain another data.frame looking like this:
Code Meaning Category Price
6152 Internet Total 4.4
6152 Internet Subtotal 3.67
4656 Tax Subtotal 0.73
6150 Phone Total 8
6150 Phone Subtotal 6.67
4656 Tax Subtotal 1.33
6151 Car Total 10
6151 Car Subtotal 8.33
4656 Tax Subtotal 1.67
Where Category displays the column from df (Total or Subtotal) and Price is displayed in the following way: Total, Subtotal, Tax showed on df.
So far I tried with:
cbind(df[1:2], stack(lapply(df[-c(1:2)], as.character)))
But it retrieves:
Meaning Code values ind
Tax 4656 0.73 Total
Internet 6152 4.4 Total
Tax 4656 1.33 Total
Phone 6150 8 Total
Tax 4656 1.67 Total
Car 6151 10 Total
Tax 4656 0.73 Tax
Internet 6152 <NA> Tax
Tax 4656 1.33 Tax
Phone 6150 <NA> Tax
Tax 4656 1.67 Tax
Car 6151 <NA> Tax
Tax 4656 <NA> Subtotal
Internet 6152 3.67 Subtotal
Tax 4656 <NA> Subtotal
Phone 6150 6.67 Subtotal
Tax 4656 <NA> Subtotal
Car 6151 8.33 Subtotal
Any ideas?
NOTE: I have tried with all this answers but because of my df having some NA the solutions do not work.
Answer 1, Answer 2, Answer 3